<?php
namespace App\Controller;
use Think\Controller;
use App\Controller\BaseController;
class UserController extends BaseController {

    /**
     * 测试数据
     * @author xuan
     * @param id midiID
     */
	public function test(){
        echo "测试";die;

        // for ($i=1; $i < 6; $i++) {
        //     $data['user_name'] = '测试考官'.$i;
        //     $data['user_nickname'] = '测试考官'.$i;
        //     $data['user_phone'] = '9999999999'.$i;
        //     $data['user_password'] = '96e79218965eb72c92a549dd5a330112';
        //     $data['user_city'] = 1;
        //     $data['user_midiclub_id'] = 1;
        //     $data['user_idcard'] = '987654321';
        //     $data['user_idpic1'] = '/Upload/image/201702/21/58abfa741affb.jpg';
        //     $data['user_email'] = 'examiner'.$i.'@163.com';
        //     $data['user_nation'] = '汉';
        //     $data['user_reg_time'] = '2017-03-06 17:40:36';
        //     $data['user_last_time'] = '2017-03-06 17:40:36';
        //     $data['user_auth'] = 3;
        //     $data['user_role'] = 4;
        //     $data['user_examiner_guitar'] = 1;
        //     $data['user_examiner_drum'] = 1;
        //     $data['user_examiner_bass'] = 1;
        //     $data['user_idaddress'] = '北京市海淀区香山瑞王坟甲12号临3号';
        //     $data['user_midigraduate'] = 1;
        //     $data['user_orgname'] = '北京迷笛音乐学校';
        //     M('user')->add($data);
        //     unset($data);
        // }
    }

    /**
     * 用户注册
     * @author xuan
     * @param user_phone    用户电话号码
     * @param user_password 密码
     */
    public function register(){
        $json_arr = $this->Security(false);
        // $json_arr['user_phone'] = 13811341067;
        // $json_arr['user_password'] = 123456;
        $data['user_phone'] = $json_arr['user_phone'];
        if(M('user')->where($data)->find()){
            $this->backToClient(101,'号码已被注册');
        }
        $json_arr['user_nickname'] = phonenumHidden($json_arr['user_phone']);
        $json_arr['user_reg_time'] = date('Y-m-d H:i:s',time());
        $json_arr['user_password'] = md5($json_arr['user_password']);
        $json_arr['user_sig'] = $this->getUserSig($json_arr['user_phone']);
        //usersig过期时间是生成以后的150天
        $json_arr['user_sigexpire'] = time() + 60*60*24*150;
        if($data['user_id'] = M('user')->data($json_arr)->add()){
            $user_arr = M('user')->where($data)->find();
            unset($user_arr['user_password']);
            $this->backToClient(1,'注册成功',$user_arr);
        }else{
            $this->backToClient(102,'注册失败');
        }
    }

    /**
     * 用户登录
     * @author xuan
     * @param user_id       用户电话号码或者midiID
     * @param user_password 用户密码
     */
    public function login(){
        $json_arr = $this->Security(false);

        //版本控制（强制更新） 1.未传版本号   2.版本号小于最新版本号
        $user_version = M('version')->where('version_client = 1')->order('version_code desc')->find();
        if (empty($json_arr['user_version'])) {
            $this->backToClient(300,'请更新到最新版本');
        }elseif ($json_arr['user_version'] < $user_version['version_code']) {
            $this->backToClient(300,'请更新到最新版本');
        }

        // $json_arr['user_id'] = '13811341066';
        // $json_arr['user_password'] = '111111';
        if($json_arr['user_id'] > 10000000){
            $json_arr['user_phone'] = $json_arr['user_id'];
            unset($json_arr['user_id']);
        }
        $json_arr['user_password'] = md5($json_arr['user_password']);
        if($user_arr = M('user')->where($json_arr)->find()){
            if (empty($user_arr['user_sig'])) {
                $data['user_sig'] = $this->getUserSig($user_arr['user_phone']);
                //usersig过期时间是生成以后的150天
                $data['user_sigexpire'] = time() + 60*60*24*150;
            }
            $data['user_last_time'] = date('Y-m-d H:i:s',time());
            $data['user_id'] = $user_arr['user_id'];
            $data['user_token'] = createRandom();
            M('user')->save($data);
            $user_arr = M('user')->where('user_id = '.$data['user_id'])->find();
            unset($user_arr['user_password']);
            $this->backToClient(1,'登录成功',$user_arr);
        }else{
            $this->backToClient(103,'账号或密码错误');
        }
    }

    /**
     * 验证密码
     * @author xuan
     * @param user_id       midiID（必传）
     * @param user_password 密码
     */
    public function checkPassword(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 6;
        // $json_arr['user_password'] = 111111;
        $json_arr['user_password'] = md5($json_arr['user_password']);
        if(M('user')->where($json_arr)->find()){
            $this->backToClient(1,'密码正确');
        }else{
            $this->backToClient(103,'账号或密码错误');
        }
    }

    /**
     * 修改个人信息
     * @author xuan
     * @param user_id       midiID（必传）
     * @param user_nickname 昵称（选填）
     * @param user_name     姓名（选填）
     * @param user_email    邮箱（选填）
     * @param user_phone    手机号码（选填）
     * @param user_avatar   头像（选填）
     * @param user_weibo    微博号（选填）
     * @param user_weixin   微信号（选填）
     */
    public function editUserinfo(){
        $json_arr = $this->Security();
        //要修改的手机号码不能是被注册过的号码
        $data['user_phone'] = $json_arr['user_phone'];
        $data['user_id'] = array('NEQ',$json_arr['user_id']);
        $user = M('user')->where($data)->find();
        if (!empty($user)) {
            $this->backToClient(103,'该手机号码已被注册');
        }
        //如果更改手机号码，则清空user_sig
        $user2 = M('user')->field('user_phone')->where('user_id = '.$json_arr['user_id'])->find();
        if ($user2['user_phone'] != $json_arr['user_phone']) {
        	$json_arr['user_sig'] = '';
        }
        M('user')->save($json_arr);
        $this->backToClient(1,'个人资料已更新');
    }

    /**
     * 获取个人信息
     * @author xuan
     * @param user_id       midiID（必传）
     */
    public function getUserinfo(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 2;
        $user = M('user')->where($json_arr)->find();
        $data['mrmidi_user_id'] = $user['user_id'];
        $data['mrmidi_auth_status'] = 1;
        if (M('mrmidi')->where($data)->find()) {
            $user['apply_status'] = 1;
        }else{
            $user['apply_status'] = 0;
        }
        if ($user) {
            $this->backToClient(1,'获取用户信息成功',$user);
        }else{
            $this->backToClient(105,'用户不存在');
        }
    }

    /**
     * 重置密码
     * @author xuan
     * @param user_phone    手机号码（必填）
     * @param user_password 密码（必填）
     */
    public function resetPassword(){
        $json_arr = $this->Security();
        $data['user_phone'] = $json_arr['user_phone'];
        $user = M('user')->field('user_id')->where($data)->find();
        if (empty($user)) {
            $this->backToClient(104,'该手机号码未被注册');
        }
        $user['user_password'] = md5($json_arr['user_password']);
        M('user')->save($user);
        $this->backToClient(1,'重置密码成功！');

    }

    /**
     * 修改密码
     * @author xuan
     * @param user_id               用户id（必填）
     * @param user_password         密码（必填）
     * @param user_newpassword      新密码（必填）
     */
    public function updatePassword(){
        $json_arr = $this->Security();
        $data['user_id'] = $json_arr['user_id'];
        $user = M('user')->field('user_id,user_password')->where($data)->find();
        if (empty($user)) {
            $this->backToClient(2,'用户不存在');
        }else{
            if (md5($json_arr['user_password']) == $user['user_password']) {
                $user['user_password'] = md5($json_arr['user_newpassword']);
                if (M('user')->save($user)) {
                    $this->backToClient(1,'修改密码成功');
                }else{
                    $this->backToClient(4,'新密码和旧密码重复');
                }
            }else{
                $this->backToClient(3,'原始密码错误');
            }
        }

    }

    /**
     * 获取城市列表
     * @author xuan
     * @param  type    1显示迷笛先生数量 2显示考场数量 0或者不传只返回城市列表
     */
    public function cityList(){
        $json_arr = $this->Security();
        if (empty($json_arr['type'])) {
            $sql = "select * from midi_city order by CONVERT( city_name USING gbk ) COLLATE gbk_chinese_ci ASC";
        }elseif ($json_arr['type'] == 1) {
            $sql = "select c.*,(select count(user_id) from midi_user where user_role in (2,3) and user_display = 1 and user_city = c.city_id) as mrmidi_count from midi_city as c";
        }elseif ($json_arr['type'] == 2) {
        	$arr2 = array();
        	//4个小时
	        $now = date('Y-m-d',time()+4*60*60);
            $sql = "select c.*,(select count(examoffline_id) from midi_examoffline as e left join midi_midiclub as m on m.midiclub_id = e.examoffline_roomid where m.midiclub_city = c.city_id and m.midiclub_display = 1 and e.examoffline_ymd > '".$now."' group by e.examoffline_roomid) as examroom_count from midi_city as c";
            $city_arr = M()->query($sql);
            foreach ($city_arr as $v) {
            	if ($v['examroom_count'] > 0) {
            		$arr2[] = $v;
            	}
            }
        	$this->backToClient(1,'获取城市列表成功',$arr2);
        }else{
            $this->backToClient(101,'未知参数错误');
        }
        $city_arr = M()->query($sql);
        $arr['city_id'] = 0;
        $arr['city_name'] = '全国';
        array_unshift($city_arr, $arr);
        $this->backToClient(1,'获取城市列表成功',$city_arr);
    }

    /**
     * 收货地址列表
     * @author xuan
     * @param address_user_id    midiID（必传）
     */
    public function addressList(){
        $json_arr = $this->Security();
        // $json_arr['address_user_id'] = 1;
        $json_arr['address_display'] = 1;
        $address_arr = M('address')->where($json_arr)->order('address_default desc')->select();
        $this->backToClient(1,'获取收货地址列表成功',$address_arr);
    }

    /**
     * 修改收货地址
     * @author xuan
     * @param address_id        地址id（必传）
     * @param address_user_id   用户midiID（必传）
     * @param address_username  收货人
     * @param address_userphone 收货人电话
     * @param address_address   收货地址
     * @param address_zipcode   邮政编码
     * @param address_default   默认地址 1默认 0非默认
     */
    public function editAddress(){
        $json_arr = $this->Security();
        // $json_arr['address_id'] = 19;
        // $json_arr['address_user_id'] = 52;
        // $json_arr['address_default'] = 0;
        if(M('address')->save($json_arr)){
            if($json_arr['address_default'] == 1){
                $sql = "update midi_address set address_default = 0 where address_user_id = ".$json_arr['address_user_id'];
                M()->execute($sql);
                $sql = "update midi_address set address_default = 1 where address_id = ".$json_arr['address_id'];
                M()->execute($sql);
            }
            $this->backToClient(1,'修改收货地址成功');
        }else{
            $this->backToClient(105,'修改收货地址失败');
        }
    }

    /**
     * 添加收货地址
     * @author xuan
     * @param address_user_id   用户midiID（必传）
     * @param address_username  收货人（必传）
     * @param address_userphone 收货人电话（必传）
     * @param address_address   收货地址（必传）
     * @param address_zipcode   邮政编码（选填）
     * @param address_default   默认地址 1默认 0非默认（选填）
     */
    public function addAddress(){
        $json_arr = $this->Security();
        if($address_id = M('address')->add($json_arr)){
            if($json_arr['address_default'] == 1){
                $sql = "update midi_address set address_default = 0 where address_user_id = ".$json_arr['address_user_id'];
                M()->execute($sql);
                $sql = "update midi_address set address_default = 1 where address_id = ".$address_id;
                M()->execute($sql);
            }
            $this->backToClient(1,'添加收货地址成功');
        }else{
            $this->backToClient(106,'添加收货地址失败');
        }
    }

    /**
     * 删除收货地址
     * @author xuan
     * @param address_id        地址id（必传）
     */
    public function deleteAddress(){
        $json_arr = $this->Security();
        $json_arr['address_display'] = 0;
        if(M('address')->save($json_arr)){
            $this->backToClient(1,'删除收货地址成功');
        }else{
            $this->backToClient(107,'删除收货地址失败');
        }
    }

    /**
     * 迷笛先生详情
     * @author xuan
     * @param mrmidi_user_id          midiID（必传）
     */
    public function mrmidiDetails(){
        $json_arr = $this->Security();
        // $json_arr['mrmidi_user_id'] = 1;
        //审核成功
        $json_arr['mrmidi_auth_status'] = 2;
        $mrmidi_arr = M('mrmidi')->alias('m')->field('m.mrmidi_major_id,m.mrmidi_level,m.mrmidi_auth_date,m.mrmidi_certificate_no,u.user_orgname,u.user_phone,u.user_weixin,u.user_introduction')->join('left join midi_user as u on m.mrmidi_user_id = u.user_id')->where($json_arr)->select();
        if (empty($mrmidi_arr)) {
            $mrmidi_arr = array();
        }
        $this->backToClient(1,'获取迷笛先生详情成功！',$mrmidi_arr);
    }

    /**
     * 获取机构列表（分页）
     * @author xuan
     * @param  midiclub_city   机构所属城市（选填）
     */
    public function orgList(){
        $json_arr = $this->Security();
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        $data['midiclub_display'] = 1;
        if (!empty($json_arr['midiclub_city'])) {
            $data['midiclub_city'] = $json_arr['midiclub_city'];
        }
        $midiclub_arr = M('midiclub')->field('midiclub_id,midiclub_name')->where($data)->page($p,$pnum)->select();
        $this->backToClient(1,'获取机构列表成功！',$midiclub_arr);
    }

    /**
     * 提交迷笛先生申请
     * @author xuan
     * @param user_id               midiID（必传）
     * @param major_id              专业id（必传）
     * @param level                 等级 1初级 2中级 3高级 4特级（必传）
     * @param link                  作品链接,没有传空字符串（必传）
     * @param orgname               所属机构名称，没有传空字符串（必传）
     * @param introduction          个人介绍,没有传空字符串（必传）
     * @param midigraduate          是否迷笛学校毕业 1是 2否（必传）
     */
    public function applyMrmidi(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 1;
        // $json_arr['major_id'] = 1;
        // $json_arr['level'] = 3;
        // $json_arr['orgname'] = '北京迷笛音乐高级学校';
        // $json_arr['link'] = 'http://www.baidu.com';
        // $json_arr['introduction'] = '我是一只小小鸟';
        // $json_arr['midigraduate'] = 1;
        $data['mrmidi_user_id'] = $json_arr['user_id'];
        $data['mrmidi_major_id'] = $json_arr['major_id'];
        if($mrmidi = M('mrmidi')->where($data)->find()){
            if($mrmidi['mrmidi_auth_status'] == 1){
                $this->backToClient(1,'您已提交申请，请等待审核结果！',2);
            }else if($mrmidi['mrmidi_auth_status'] == 2){
                $this->backToClient(1,'您已通过审核！',3);
            }else if($mrmidi['mrmidi_auth_status'] == 3){
                $where['mrmidi_link'] = $json_arr['link'];
                $where['mrmidi_level'] = $json_arr['level'];
                $where['mrmidi_auth_status'] = 1;
                $where['mrmidi_id'] = $mrmidi['mrmidi_id'];
                $where['mrmidi_applytime'] = time();
                if(M('mrmidi')->save($where)){
                    $where_user['user_id'] = $json_arr['user_id'];
                    $where_user['user_orgname'] = $json_arr['orgname'];
                    $where_user['user_introduction'] = $json_arr['introduction'];
                    $where_user['user_midigraduate'] = $json_arr['midigraduate'];
                    M('user')->save($where_user);
                    $this->backToClient(1,'提交申请成功！');
                }else{
                    $this->backToClient(1,'提交迷笛先生申请失败！',4);
                }
            }
        }
        $data['mrmidi_link'] = $json_arr['link'];
        $data['mrmidi_level'] = $json_arr['level'];
        $data['mrmidi_applytime'] = time();
        if(M('mrmidi')->add($data)){
            $user_arr = M('user')->field('user_id,user_orgname,user_introduction,user_midigraduate')->where('user_id = '.$json_arr['user_id'])->find();
            $user_arr['user_orgname'] = $json_arr['orgname'];
            $user_arr['user_introduction'] = $json_arr['introduction'];
            $user_arr['user_midigraduate'] = $json_arr['midigraduate'];
            M('user')->save($user_arr);
            $this->backToClient(1,'提交申请成功！');
        }else{
            $this->backToClient(4,'提交迷笛先生申请失败！',4);
        }
    }

    /**
     * 获取其他文章列表
     * @author xuan
     */
    public function articleOther(){
        $json_arr = $this->Security();
        $data['article_type'] = 6;
        $article_arr = M('Article')->field('article_id,article_title,article_url,article_pic')->where($data)->select();
        foreach ($article_arr as $k => $v) {
            $article_arr[$k]['article_url'] = 'http://47.93.115.108/index.php/App/User/article_details/id/'.$v['article_id'];
        }
        $this->backToClient(1,'获取其他文章列表成功！',$article_arr);
    }

    /**
     * 获取轮播图列表
     * @author xuan
     * @param banner_position   	位置 1首页 2考级 3迷笛club（必填）
     * @param banner_midiclub_id    迷笛club ID（type=3必填）
     */
    public function bannerList(){
        $json_arr = $this->Security();
        $json_arr['banner_display'] = 1;
        $json_arr = array_filter($json_arr);
        // $json_arr['banner_position'] = 1;
        $banner_arr = M('banner')->where($json_arr)->order('banner_id desc')->limit(3)->select();
        $this->backToClient(1,'获取轮播图列表成功！',$banner_arr);
    }

    /**
     * 获取音频列表（分页）
     * @author xuan
     * @param audio_major_id    专业 1电吉他 2爵士鼓 3电贝司（必传）
     * @param audio_level       等级 1-9（选传）
     */
    public function audioList(){
        $json_arr = $this->Security();
        // $json_arr['audio_major_id'] = 1;
        // $json_arr['audio_level'] = 1;
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        $data['audio_display'] = 1;
        $data['audio_major_id'] = $json_arr['audio_major_id'];
        $data['audio_level'] = $json_arr['audio_level'];
        $audio_arr = M('audio')->where($data)->page($p,$pnum)->order('audio_level asc')->select();
        $this->backToClient(1,'获取音频列表成功！',$audio_arr);
    }

    /**
     * 获取视频列表（分页）
     * @author xuan
     * @param video_major_id    专业 1电吉他 2爵士鼓 3电贝司（必传）
     * @param video_level       等级 1-9
     */
    public function videoList(){
        $json_arr = $this->Security();
        // $json_arr['video_major_id'] = 3;
        // $json_arr['video_level'] = 3;
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        $data['video_display'] = 1;
        $data['video_major_id'] = $json_arr['video_major_id'];
        $data['video_level'] = $json_arr['video_level'];
        $video_arr = M('video')->where($data)->page($p,$pnum)->order('video_level asc,video_order desc')->select();
        $this->backToClient(1,'获取视频列表成功！',$video_arr);
    }

    /**
     * 获取场地列表(分页)
     * @author xuan
     * @param midiclub_city     城市id（必传）
     * @param midiclub_level    等级 1初级 2中级 3高级 4特级
     * @param midiclub_type     类型 1midiclub 2考场（必填）
     * @param my_lng            我的经度
     * @param my_lat            我的纬度
     * @param midiclub_name     名称
     */
    public function midiclubList(){
        $json_arr = $this->Security();
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        $json_arr['midiclub_display'] = 1;
        // $json_arr['midiclub_type'] = 2;
        // $json_arr['midiclub_city'] = 1;
        if ($midiclub_name = $json_arr['midiclub_name']) {
            $json_arr['midiclub_name'] = array('like',"%{$midiclub_name}%");
        }
        if($json_arr['midiclub_type'] == 1){
            $json_arr['midiclub_type'] = array('IN','1,3');
        }elseif ($json_arr['midiclub_type'] == 2) {
            $json_arr['midiclub_type'] = array('IN','2,3');
        }else{
            $this->backToClient(114,'未选择场地类型');
        }
        $midiclub_arr = M('midiclub')->where($json_arr)->page($p,$pnum)->select();
        $midiclubs = array();
        foreach ($midiclub_arr as $k => $v) {
            $v['distance'] = getDistance($json_arr['my_lat'],$json_arr['my_lng'],$v['midiclub_lat'],$v['midiclub_lng']);
            array_push($midiclubs, $v);
        }
        foreach ($midiclubs as $k => $v) {
            $distance[$k] = $v['distance'];
        }
        array_multisort($distance,SORT_ASC,$midiclubs);
        $this->backToClient(1,'获取场地列表成功！',$midiclubs);
    }

    /**
     * 报名付款（废弃，应写在支付回调函数中）
     * @author xuan
     * @param exam_id        考试id（必填）
     */
    public function payExam(){
        $json_arr = $this->Security();
        // $json_arr['exam_paystatus'] = 2;
        // $json_arr['exam_status'] = 1;
        // $json_arr['exam_cost'] = 200;
        if(M('exam')->save($json_arr)){
            $exam_arr = M('exam')->where('exam_id = '.$json_arr['exam_id'])->find();
            $this->backToClient(1,'报名费付款成功',$exam_arr);
        }else{
            $this->backToClient(117,'报名费付款失败！');
        }
    }

    /**
     * 我的考试
     * @author xuan
     * @param user_id        考生id（必填）
     * @param status         考生状态 1已报名 3已完成
     */
    public function myExam(){
        $json_arr = $this->Security();
        $data['exam_user_id'] = $json_arr['user_id'];
        $data['exam_status'] = $json_arr['status'];
        if ($data != array_filter($data)) {
            $this->backToClient(2,'参数不全');
        }
        $exam_arr = M('exam')->alias('e')->join('left join midi_midiclub as m on e.exam_midiclub_id = m.midiclub_id')->join('left join midi_examtime as t on e.exam_time = t.examtime_id')->field('e.exam_id,e.exam_major_id,e.exam_level,e.exam_ymd,t.examtime_time,e.exam_midiclub_id,m.midiclub_name,e.exam_result,e.exam_comment,u.user_id,u.user_phone')->join('left join midi_user as u on e.exam_examiner_id = u.user_id')->where($data)->order('e.exam_id desc')->select();
        if (empty($exam_arr)) {
            $exam_arr = array();
        }
        $this->backToClient(1,'获取考试信息成功',$exam_arr);
    }

    /**
     * 我的收藏
     * @author xuan
     * @param user_id               考生id（必填）
     */
    public function myCollection(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 1;
        $video_ids = M('user')->where($json_arr)->getField('user_collection');
        if (empty($video_ids)) {
            $video_arr = array();
        }else{
            $data['video_id'] = array('IN',$video_ids);
            $video_arr = M('video')->where($data)->order('video_id desc')->select();
        }
        $this->backToClient(1,'获取我的收藏成功',$video_arr);
    }

    /**
     * 检查是否已收藏
     * @author xuan
     * @param user_id               考生id（必填）
     * @param video_id              视频id（必填）
     */
    public function checkCollection(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 7;
        // $json_arr['video_id'] = 1;
        $video_ids = M('user')->where($json_arr)->getField('user_collection');
        $video_arr = explode(',', $video_ids);
        if(in_array($json_arr['video_id'], $video_arr)){
            $this->backToClient(1,'已收藏',1);
        }else{
            $this->backToClient(1,'未收藏',2);
        }
    }

    /**
     * 添加收藏
     * @author xuan
     * @param user_id               考生id（必填）
     * @param video_id              视频id（必填）
     */
    public function addCollection(){
        $json_arr = $this->Security();
        $video_ids = M('user')->where($json_arr)->getField('user_collection');
        if(empty($video_ids)){
            $data['user_collection'] = $json_arr['video_id'];
        }else{
            $data['user_collection'] = $video_ids.','.$json_arr['video_id'];
        }
        $data['user_id'] = $json_arr['user_id'];
        if(M('user')->save($data)){
            //视频收藏数+1
            $sql = "update midi_video set video_collect_count = video_collect_count + 1 where video_id = ".$json_arr['video_id'];
            M()->execute($sql);
            $this->backToClient(1,'添加收藏成功',1);
        }else{
            $this->backToClient(1,'添加收藏失败！',2);
        }
    }

    /**
     * 删除收藏（支持多删单删）
     * @author xuan
     * @param user_id               考生id（必填）
     * @param type                  类型 1单删 2多删（必填）
     * @param video_id              视频id（单删的时候必填）
     */
    public function deleteCollection(){
        $json_arr = $this->Security();
        $data['user_id'] = $json_arr['user_id'];
        if ($json_arr['type'] == 1) {
            $video_ids = M('user')->where($data)->getField('user_collection');
            $collection_arr = explode(',', $video_ids);
            $key = array_search($json_arr['video_id'], $collection_arr);
            unset($collection_arr[$key]);
            $data['user_collection'] = implode(',', $collection_arr);
            M('user')->save($data);
            $this->backToClient(1,'删除收藏成功');
        }elseif ($json_arr['type'] == 2) {
            $data['user_collection'] = '';
            M('user')->save($data);
            $this->backToClient(1,'清空收藏成功');
        }else{
            $this->backToClient(2,'类型参数错误');
        }
    }

    /**
     * 迷笛先生列表(分页)
     * @author xuan
     * @param mrmidi_major_id       专业id
     * @param mrmidi_level          专业等级
     * @param user_sex              性别 1男 2女
     * @param user_city             城市
     * @param user_name             姓名
     */
    public function mrmidiList(){
        $json_arr = $this->Security();
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;

        $where['user_role'] = array('IN','2,3');
        $where['user_display'] = 1;
        if ($json_arr['user_sex']) {
            $where['user_sex'] = $json_arr['user_sex'];
        }
        if ($json_arr['user_city']) {
            $where['user_city'] = $json_arr['user_city'];
        }
        if ($json_arr['user_name']) {
            $where['user_name'] = array('LIKE',"%{$json_arr['user_name']}%");
        }
        $user_arr = M('user')->where($where)->page($p,$pnum)->select();
        $result = array();
        foreach ($user_arr as $k => $v) {
            $data['mrmidi_user_id'] = $v['user_id'];
            $data['mrmidi_auth_status'] = 2;
            if ($json_arr['mrmidi_major_id']) {
                $data['mrmidi_major_id'] = $json_arr['mrmidi_major_id'];
            }
            if ($json_arr['mrmidi_level']) {
                $data['mrmidi_level'] = $json_arr['mrmidi_level'];
            }
            if (M('mrmidi')->where($data)->select()) {
                unset($data['mrmidi_major_id']);
                unset($data['mrmidi_level']);
                $mrmidi_arr = M('mrmidi')->where($data)->select();
                foreach ($mrmidi_arr as $key => $value) {
                    if ($value['mrmidi_major_id'] == 1) {
                        $v['guitar'] = $value;
                    }elseif ($value['mrmidi_major_id'] == 2) {
                        $v['drum'] = $value;
                    }elseif ($value['mrmidi_major_id'] == 3) {
                        $v['bass'] = $value;
                    }
                }
                array_push($result, $v);
            }
        }
        $this->backToClient(1,'获取迷笛先生列表成功',$result);
    }

    /**
     * 意见反馈
     * @author xuan
     * @param suggest_user_id       用户midiID（必填）
     * @param suggest_type          类型 1信息举报 2完善建议 3相关咨询 4考级反馈 5其他问题（必填）
     * @param suggest_content       反馈信息（必填）
     * @param suggest_pic1          图1（选填）
     * @param suggest_pic2          图2（选填）
     * @param suggest_pic3          图3（选填）
     */
    public function suggest(){
        $json_arr = $this->Security();
        $json_arr['suggest_time'] = date('Y-m-d H:i:s',time());
        if(M('suggest')->add($json_arr)){
            $this->backToClient(1,'意见反馈发表成功');
        }else{
            $this->backToClient(121,'意见反馈发表失败！');
        }
    }

    /**
     * 加入购物车
     * @author xuan
     * @param shoppingcart_user_id      用户midiID（必填）
     * @param shoppingcart_goods_id     商品id（必填）
     * @param shoppingcart_quantity     数量（必填）
     */
    public function addShoppingcart(){
        $json_arr = $this->Security();
        // $json_arr['shoppingcart_user_id'] = 2;
        // $json_arr['shoppingcart_goods_id'] = 4;
        // $json_arr['shoppingcart_quantity'] = 1;
        $data['shoppingcart_user_id'] = $json_arr['shoppingcart_user_id'];
        //购物车表中有该用户
        if($cart = M('shoppingcart')->where($data)->find()){
            $details = $cart['shoppingcart_details'];
            //如果购物车是空的
            if (empty($details)) {
                $where['shoppingcart_details'] = $json_arr['shoppingcart_goods_id'].':'.$json_arr['shoppingcart_quantity'];
                $where['shoppingcart_id'] = $cart['shoppingcart_id'];
                if (M('shoppingcart')->save($where)) {
                    $this->backToClient(1,'添加购物车成功！');
                }else{
                    $this->backToClient(122,'添加购物车失败！');
                }
            }else{  //如果购物车不是空的
                $details_arr = explode(',', $details);
                $arr = array();
                $tag = 0;
                foreach ($details_arr as $k => $v) {
                    $d = explode(':', $v);
                    //如果购物车中存在该商品
                    if ($d[0] == $json_arr['shoppingcart_goods_id']) {
                        $d[1] += $json_arr['shoppingcart_quantity'];
                        $v = implode(':', $d);
                        $tag = 1;
                    }
                    array_push($arr, $v);
                }
                $details_str = implode(',', $arr);
                if ($tag == 0) {
                    $details_str .= ','.$json_arr['shoppingcart_goods_id'].':'.$json_arr['shoppingcart_quantity'];
                }
                $where['shoppingcart_details'] = $details_str;
                $where['shoppingcart_id'] = $cart['shoppingcart_id'];
                if (M('shoppingcart')->save($where)) {
                    $this->backToClient(1,'添加购物车成功！');
                }else{
                    $this->backToClient(122,'添加购物车失败！');
                }
            }
        }else{  //购物车表中没有该用户，表中添加一条信息
            $data['shoppingcart_details'] = $json_arr['shoppingcart_goods_id'].':'.$json_arr['shoppingcart_quantity'];
            if (M('shoppingcart')->add($data)) {
                $this->backToClient(1,'添加购物车成功！');
            }else{
                $this->backToClient(122,'添加购物车失败！');
            }
        }
    }

    /**
     * 查看购物车（待付款）
     * @author xuan
     * @param shoppingcart_user_id       用户midiID（必填）
     */
    public function shoppingcartList(){
        $json_arr = $this->Security();
        // $json_arr['shoppingcart_user_id'] = 1;
        //运费
        $freight = M('freight')->find();
        $freight_price = $freight['freight_price'];
        //如果购物车存在
        if ($cart = M('shoppingcart')->where($json_arr)->find()) {
            //有购物车，购物车中无商品
            if (empty($cart['shoppingcart_details'])) {
                $this->backToClient(1,'购物车是空的');
            }else{//购物车中有商品
                $details = $cart['shoppingcart_details'];//'1:4,2:3,3:5'
                $details_arr = explode(',', $details);
                $shoppingcart_details = array();
                foreach ($details_arr as $k => $v) {
                    $d = explode(':', $v);
                    $goods_arr = M('goods')->field('goods_id,goods_num,goods_name,goods_price,goods_pic')->where('goods_id = '.$d[0])->find();
                    $goods_arr['quantity'] = $d[1];
                    $goods_arr['freight'] = $freight_price;
                    array_push($shoppingcart_details, $goods_arr);
                }
                $this->backToClient(1,'获取购物车列表成功！',$shoppingcart_details);
            }
        }else{//没有购物车，创建购物车
            M('shoppingcart')->add($json_arr);
            $this->backToClient(1,'购物车是空的');
        }
    }

    /**
     * 全部搜索
     * @author xuan
     * @param search_type       搜索类型（必填）1 所有（音频，视频，迷笛先生，迷笛club） 2证书
     * @param search_name       关键字（选填）
     */
    public function searchall(){
        $json_arr = $this->Security();
        $search_type = $json_arr['search_type'];
        $search_name = $json_arr['search_name'];
        // $search_type = 1;
        // $search_name = '1';
        $result = array();
        switch ($search_type) {
            case 1:
                $audio_data['audio_name'] = array('like',"%{$search_name}%");
                $audio_arr = M('audio')->field('audio_id,audio_name,audio_major_id,audio_introduction,audio_pic')->where($audio_data)->limit(3)->select();
                $video_data['video_name'] = array('like',"%{$search_name}%");
                $video_arr = M('video')->field('video_id,video_name,video_pic,video_introduction')->where($video_data)->limit(3)->select();
                $where['user_role'] = array('IN','2,3');
                $where['user_display'] = 1;
                if ($json_arr['user_name']) {
                    $where['user_name'] = array('LIKE',"%{$json_arr['search_name']}%");
                }
                $user_arr = M('user')->field('user_id,user_name,user_nickname')->where($where)->select();
                $mr_arr = array();
                foreach ($user_arr as $k => $v) {
                    $data['mrmidi_user_id'] = $v['user_id'];
                    $data['mrmidi_auth_status'] = 2;
                    $mrmidi_arr = M('mrmidi')->where($data)->select();
                    foreach ($mrmidi_arr as $key => $value) {
                        if ($value['mrmidi_major_id'] == 1) {
                            $v['guitar'] = $value;
                        }elseif ($value['mrmidi_major_id'] == 2) {
                            $v['drum'] = $value;
                        }elseif ($value['mrmidi_major_id'] == 3) {
                            $v['bass'] = $value;
                        }
                    }
                    array_push($mr_arr, $v);
                }
                $midiclub_data['midiclub_name'] = array('like',"%{$search_name}%");
                $midiclub_data['midiclub_type'] = array('IN',"1,3");
                $midiclub_data['midiclub_display'] = 1;
                $midiclub_arr = M('midiclub')->field('midiclub_id,midiclub_name,midiclub_level,midiclub_pic')->where($midiclub_data)->limit(3)->select();
                if (empty($audio_arr)) {
                    $audio_arr = array();
                }
                if (empty($video_arr)) {
                    $video_arr = array();
                }
                if (empty($midiclub_arr)) {
                    $midiclub_arr = array();
                }
                $result['audio'] = $audio_arr;
                $result['video'] = $video_arr;
                $result['mrmidi'] = $mr_arr;
                $result['midiclub'] = $midiclub_arr;
                $this->backToClient(1,'搜索成功',$result);
                break;
            case 2:
                $data['mrmidi_certificate_no'] = $search_name;
                if ($mrmidi_arr = M('mrmidi')->field('m.*,u.user_name,u.user_sex')->alias('m')->join('left join midi_user as u on m.mrmidi_user_id = u.user_id')->where($data)->find()) {
                    $this->backToClient(1,'搜索成功',$mrmidi_arr);
                }else{
                    $this->backToClient(124,'没有此证书');
                }
                break;
            default:
                $this->backToClient(123,'输入搜索类型错误');
                break;
        }
    }

    /**
     * 音频下载量+1
     * @author xuan
     * @param audio_id          音频id（必填）
     */
    public function audioDownloadCount(){
        $json_arr = $this->Security();
        // $json_arr['audio_id'] = 1;
        if (empty($json_arr['audio_id'])) {
        	$this->backToClient(2,'参数不全');
        }
        $sql = "update midi_audio set audio_download_count = audio_download_count + 1 where audio_id = ".$json_arr['audio_id'];
        M()->execute($sql);
        $this->backToClient(1,'音频下载量+1');
    }

    /**
     * 增加评论
     * @author xuan
     * @param comment_user_id       评论者的midiID（必填）
     * @param comment_object        评论对象 1用户 2音频（必填）
     * @param comment_object_id     评论对象id（必填）
     * @param comment_content       评论内容（必填）
     */
    public function comment(){
        $json_arr = $this->Security();
        $json_arr['comment_date'] = date('Y-m-d H:i:s');
        if (M('comment')->add($json_arr)) {
            $this->backToClient(1,'添加评论成功');
        }else{
            $this->backToClient(125,'添加评论失败！');
        }
    }

    /**
     * 查看评论（分页）
     * @author xuan
     * @param comment_object        评论对象 1用户 2音频（必填）
     * @param comment_object_id     评论对象id（必填）
     */
    public function commentList(){
        $json_arr = $this->Security();
        // $json_arr['comment_object'] = 1;
        // $json_arr['comment_object_id'] = 1;
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        $data['comment_object'] = $json_arr['comment_object'];
        $data['comment_object_id'] = $json_arr['comment_object_id'];
        $comment_arr = M('comment')->alias('c')->field('c.*,u.user_avatar,u.user_name')->join('left join midi_user as u on c.comment_user_id = u.user_id')->where($data)->order('comment_id desc')->page($p,$pnum)->select();
        if (empty($comment_arr)) {
            $comment_arr = array();
        }
        $this->backToClient(1,'获取评论列表成功！',$comment_arr);
    }

    /**
     * 消息列表(分页)
     * @author xuan
     * @param message_user_id       midiID（必填）
     */
    public function messageList(){
        $json_arr = $this->Security();
        // $json_arr['message_user_id'] = 42;
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        if (empty($json_arr['message_user_id'])) {
            $this->backToClient(2,'参数不全');
        }
        $reg_time = M('user')->where('user_id = '.$json_arr['message_user_id'])->getField('user_reg_time');
        $time = strtotime($reg_time);
        //考生端或者系统消息
        $data['message_display'] = 1;
        $data['message_client'] = 1;
        $data['message_time'] = array('GT',$time);
        $message_arr = M('message')->where($data)->where('message_user_id = '.$json_arr['message_user_id'].' or message_type = -1')->page($p,$pnum)->order('message_id desc')->select();
        $this->backToClient(1,'获取消息列表成功！',$message_arr);
    }

    /**
     * 运费金额
     * @author xuan
     */
    public function freight(){
        $json_arr = $this->Security();
        $freight = M('freight')->find();
        $this->backToClient(1,'获取运费成功！',$freight);
    }

    /**
     * 查看当前时间段是否有老师监考
     * @author xuan
     * @param examoptions_ymd       考试年月日（必填）
     * @param time                  时间段（必填）
     */
    public function timeAllow(){
        $json_arr = $this->Security();
        $json_arr['examoptions_ymd'] = '2016-09-21';
        $json_arr['time'] = 1;
        $data['examoptions_ymd'] = $json_arr['examoptions_ymd'];
        $examoptions_arr = M('examoptions')->where($data)->select();
        if (empty($examoptions_arr)) {
            $this->backToClient(126,'当前时间段没有监考老师！');
        }
        $examiner_ids = array();
        foreach ($examoptions_arr as $k => $v) {
            $time_arr = explode(',', $v['examoptions_time']);
            $ordertime_arr = explode(',', $v['examoptions_ordertime']);
            if (in_array($json_arr['time'], $time_arr) && !in_array($json_arr['time'], $ordertime_arr)) {
                array_push($examiner_ids, $v['examoptions_user_id']);
            }
        }
        if (empty($examiner_ids)) {
            $this->backToClient(126,'当前时间段没有监考老师！');
        }else{
            //array_rand返回键名
            $key = array_rand($examiner_ids);
            $result['exam_examiner_id'] = $examiner_ids[$key];
            $this->backToClient(1,'获取监考老师成功！',$result);
        }
    }

    /**
     * 生成试卷(乐理)
     * @author xuan
     */
    public function createExampaper(){
        $json_arr = $this->Security();
        $data['examquestion_display'] = 1;      //显示
        $data['examquestion_category'] = 1;     //练习
        //limit中的值是考题数量
        $ta = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 1')->order('rand()')->limit(8)->select();
        $tb = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 2')->order('rand()')->limit(2)->select();
        $tc = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 3')->order('rand()')->limit(10)->select();
        $td = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 4')->order('rand()')->limit(8)->select();
        $te = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 5')->order('rand()')->limit(8)->select();
        $tf = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 6')->order('rand()')->limit(5)->select();
        $tg = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 7')->order('rand()')->limit(10)->select();
        $th = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 8')->order('rand()')->limit(5)->select();
        $this->assign('ta',$ta);
        $this->assign('tb',$tb);
        $this->assign('tc',$tc);
        $this->assign('td',$td);
        $this->assign('te',$te);
        $this->assign('tf',$tf);
        $this->assign('tg',$tg);
        $this->assign('th',$th);
        $this->display();
    }

    /**
     * 生成试卷(听力)
     * @author xuan
     */
    public function createExampaper2(){
        $json_arr = $this->Security();
        $data['examquestion_display'] = 1;      //显示
        $data['examquestion_category'] = 1;     //练习
        //limit中的值是考题数量
        $tl = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 12')->order('rand()')->limit(1)->select();
        $tm = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 13')->order('rand()')->limit(5)->select();
        $tn = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 14')->order('rand()')->limit(5)->select();
        $to = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 15')->order('rand()')->limit(5)->select();
        $this->assign('tl',$tl);
        $this->assign('tm',$tm);
        $this->assign('tn',$tn);
        $this->assign('to',$to);
        $this->display();
    }

    /**
     * 生成试卷(视唱)
     * @author xuan
     */
    public function createExampaper3(){
        $json_arr = $this->Security();
        $data['examquestion_display'] = 1;      //显示
        $data['examquestion_category'] = 1;     //练习
        //limit中的值是考题数量
        $ti = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 9')->order('rand()')->limit(2)->select();
        $tj = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 10')->order('rand()')->limit(5)->select();
        $tk = M('examquestion')->where($data)->where('examquestion_examquestiontype_id = 11')->order('rand()')->limit(5)->select();
        $this->assign('ti',$ti);
        $this->assign('tj',$tj);
        $this->assign('tk',$tk);
        $this->display();
    }

    /**
     * 考试分数
     * @author xuan
     */
    public function examScore(){
        $question_nums = '';
        $results = array();
        foreach ($_POST as $k => $v) {
            if (empty($question_nums)) {
                $question_nums = $k;
            }else{
                $question_nums .= ','.$k;
            }
            $arr['examquestion_id'] = $k;
            $arr['examquestion_result'] = $v;
            array_push($results, $arr);
        }
        $data['examquestion_id'] = array('IN',$question_nums);
        $data['examquestion_display'] = 1;
        $answer_arr = M('examquestion')->alias('e')->field('e.examquestion_id,e.examquestion_type,e.examquestion_answer,t.examquestiontype_score')->join('left join midi_examquestiontype as t on e.examquestion_examquestiontype_id = t.examquestiontype_id')->where($data)->select();
        $merge = array();
        foreach ($answer_arr as $k => $v) {
            foreach ($results as $key => $value) {
                if ($v['examquestion_id'] == $value['examquestion_id']) {
                    $arr = array_merge($v,$value);
                    array_push($merge, $arr);
                }
            }
        }
        $total_score = 0;
        foreach ($merge as $k => $v) {
            if ($v['examquestion_type'] == 1) {      //选择题
                if ($v['examquestion_result'] == $v['examquestion_answer']) {
                    $total_score += $v['examquestiontype_score'];
                }
            }elseif ($v['examquestion_type'] == 2) { //填空题
                $answer_arr = explode(',', $v['examquestion_answer']);
                $result_arr = explode(',', $v['examquestion_result']);
                foreach ($answer_arr as $k1 => $v1) {
                    if ($v1 == $result_arr[$k1]) {
                        $total_score += $v['examquestiontype_score'];
                    }
                }
            }elseif ($v['examquestion_type'] == 3) { //视唱题

            }
        }
        $this->assign('total_score',$total_score);
        $this->display();
    }

    /**
     * 快递公司列表
     * @author xuan
     * @param expName            快递/物流公司名称（选填）
     * @param maxSize            分页时,每页返回的最大记录数（选填）
     * @param page               分页的页数（选填）
     */
    public function expressList(){
        $json_arr = $this->Security();
        $expName = $json_arr['expName'];
        $maxSize = $json_arr['maxSize'];
        $page = $json_arr['page'];

        echo expressList($expName,$maxSize,$page);
    }

    /**
     * 快递订单查询
     * @author xuan
     * @param com     必填       填写auto则自动识别（对应"快递公司查询"接口中的simpleName快递公司简称）
     * @param nu      必填       运单号
     */
    public function expressInfo(){
        $json_arr = $this->Security();
        // $json_arr['com'] = 'shentong';
        // $json_arr['nu'] = '402314705800';
        $company = strval($json_arr['com']);
        $number = strval($json_arr['nu']);
        $str = expressInfo($company,$number);
        $arr = json_decode($str,true);
        $this->backToClient(1,'快递订单查询成功',$arr);
    }

    /**
     * 身份证照片识别(三方接口)
     * @author      xuan
     * @param       file            身份证图片(必传)
     * @param       user_id         用户id(必传)
     */
    public function idauth(){
        $json_arr = $this->Security();
        $finfo = upload($_FILES['file']);
        if ($finfo['status'] == 0) {
            $this->backToClient(4,$finfo['msg']);
        }else{
            $imgurl = C(DOMAIN_NAME).$finfo['filepath'];
            $imgcontent = file_get_contents($imgurl);
            $imgbase64 = base64_encode($imgcontent);
            $result_json = idAuth($imgbase64);
            $result = json_decode($result_json,true);
            if ($result['code'] == 0) {
                $result['user_idpic1'] = $finfo['filepath'];
                //身份证头像截取存入user表中
                // $headImage = base64_decode($result['headImage']);
                // $headImage_url = './Public/assets/avatars/'.uniqid().'.jpg';
                // file_put_contents($headImage_url, $headImage);
                // $headImage_url = substr($headImage_url, 1);
                // $data['user_id'] = $json_arr['user_id'];
                // $data['user_avatar'] = $headImage_url;
                // M('user')->save($data);
                unset($result['croppedImage']);
                unset($result['headImage']);
                $this->backToClient(1,'获取身份信息成功',$result);
            }else{
                $this->backToClient($result['code'],$result['result']);
            }
        }
    }

    /**
     * 身份证照片识别(三方接口)
     * @author      xuan
     * @param       file            身份证图片(必传)
     * @param       user_id         用户id(必传)
     */
    public function idauthtest(){
        $imgurl = C(DOMAIN_NAME).'/id.jpg';
        $imgcontent = file_get_contents($imgurl);
        $imgbase64 = base64_encode($imgcontent);
        $result_json = idAuth($imgbase64);
        $result = json_decode($result_json,true);
        if ($result['code'] == 0) {
            $result['user_idpic1'] = $finfo['filepath'];
            //身份证头像截取存入user表中
            // $headImage = base64_decode($result['headImage']);
            // $headImage_url = '/Public/assets/avatars/'.uniqid().'jpg';
            // file_put_contents($headImage_url, $headImage);
            // $data['user_id'] = $json_arr['user_id'];
            // $data['user_avatar'] = $headImage_url;
            // M('user')->save($data);
            unset($result['croppedImage']);
            unset($result['headImage']);
            $this->backToClient(1,'获取身份信息成功',$result);
        }else{
            $this->backToClient($result['code'],$result['result']);
        }
    }

    /**
     * 提交验证身份信息
     * @author xuan
     * @param user_id           midiID（必传）
     * @param user_name         姓名（必传）
     * @param user_sex          性别 1男 2女（必传）
     * @param user_birthday     生日 格式 2016-01-01（必传）
     * @param user_nation       民族（必传）
     * @param user_email        邮箱（必传）
     * @param user_idaddress    所在地 城市id（必传）
     * @param user_idcard       身份证号（必传）
     * @param user_idpic1       身份证件照（必传）
     * @param type              验证类型 1通过三方接口认证 2没有身份证验证提交（必传）
     */
    public function submitAuthinfo(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 7;
        // $json_arr['user_name'] = '小丸子';
        // $json_arr['user_sex'] = 2;
        // $json_arr['user_birthday'] = '1999-01-01';
        // $json_arr['user_nation'] = '汉族';
        // $json_arr['user_email'] = 'xiaowanzi@126.com';
        // $json_arr['user_city'] = 1;
        // $json_arr['user_idcard'] = 110105199901011234;
        // $json_arr['user_idpic1'] = '/midi/uploads/default_avatar.jpg';
        // $json_arr['user_idpic2'] = '/midi/uploads/default_avatar.jpg';
        if (empty($json_arr['type'])) {
            $this->backToClient(2,'验证类型必传');
        }
        if(M('user')->save($json_arr)){
            $data['user_id'] = $json_arr['user_id'];
            if ($json_arr['type'] == 1) {
                $data['user_auth'] = 3;
            }elseif ($json_arr['type'] == 2) {
                $data['user_auth'] = 2;
            }else{
                $this->backToClient(3,'验证类型错误');
            }
            M('user')->save($data);
            unset($data['user_auth']);
            $user_arr = M('user')->where($data)->find();
            $this->backToClient(1,'提交验证身份信息成功！',$user_arr);
        }else{
            $this->backToClient(108,'提交验证身份信息失败！');
        }
    }

    /**
     * search（发现）
     * @author xuan
     * @param type          类型 1迷笛先生 2迷笛club 3考场（必传）
     * @param city          城市id（选传）
     * @param midiclub      迷笛club id（选传）
     * @param user_name     迷笛先生真实姓名（选传）
     * @param sex           迷笛先生性别 1男 2女（选传）
     * @param major_id      迷笛先生专业 1电吉他 2爵士鼓 3电贝司（选传）
     * @param level         迷笛先生等级 1初级 2中级 3高级（选传）
     * @param club_name     迷笛CLUB名称（选传）
     * @param my_lng        我的坐标-经度（选传）
     * @param my_lat        我的坐标-纬度（选传）
     */
    public function search(){
        $json_arr = $this->Security();
        $json_arr = array_filter($json_arr);
        // $json_arr['type'] = 2;
        // $json_arr['midiclub'] = 2;
        $search_type = $json_arr['type'];
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        switch ($search_type) {
            //搜索迷笛先生
            case '1':
                $data_sir['user_role'] = array('IN','2,3');
                $data_sir['user_display'] = 1;
                $data_sir['mrmidi_auth_status'] = 2;
                if (!empty($json_arr['city'])) {
                    $data_sir['user_city'] = $json_arr['city'];
                }
                if (!empty($json_arr['user_name'])) {
                    $data_sir['user_name'] = array('LIKE',"%{$json_arr['user_name']}%");
                }
                if (!empty($json_arr['sex'])) {
                    $data_sir['user_sex'] = $json_arr['sex'];
                }
                if (!empty($json_arr['major_id'])) {
                    $data_sir['mrmidi_major_id'] = $json_arr['major_id'];
                }
                if (!empty($json_arr['level'])) {
                    $data_sir['mrmidi_level'] = $json_arr['level'];
                }
                if (!empty($json_arr['club_name'])) {
                    $data_sir['midiclub_name'] = array('LIKE',"%{$json_arr['club_name']}%");
                }
                $mrmidi_arr = M('mrmidi')->alias('m')->join('left join midi_user as u on m.mrmidi_user_id = u.user_id')->join('left join midi_city as c on u.user_city = c.city_id')->join('left join midi_midiclub as mc on u.user_midiclub_id = mc.midiclub_id')->field('u.user_id,u.user_avatar,u.user_name,u.user_sex,u.user_phone,u.user_orgname,u.user_weixin,u.user_introduction,u.user_midiclub_id,mc.midiclub_name,c.city_name')->where($data_sir)->page($p,$pnum)->group('u.user_id')->select();
                if (empty($mrmidi_arr)) {
                    $mrmidi_arr = array();
                }else{
                    foreach ($mrmidi_arr as $k => $v) {
                        $mr['mrmidi_user_id'] = $v['user_id'];
                        $mr['mrmidi_auth_status'] = 2;
                        $mrmidi = M('mrmidi')->field('mrmidi_major_id,mrmidi_level')->where($mr)->select();
                        foreach ($mrmidi as $key => $value) {
                            if ($value['mrmidi_major_id'] == 1) {
                            $mrmidi_arr[$k]['mrmidi_guitar_level'] = $value['mrmidi_level'];
                            }elseif ($value['mrmidi_major_id'] == 2) {
                                $mrmidi_arr[$k]['mrmidi_drum_level'] = $value['mrmidi_level'];
                            }elseif ($value['mrmidi_major_id'] == 3) {
                                $mrmidi_arr[$k]['mrmidi_bass_level'] = $value['mrmidi_level'];
                            }
                        }
                    }
                }
                $this->backToClient(1,'获取迷笛先生列表成功',$mrmidi_arr);
                break;
            //搜索迷笛club
            case '2':
                $data_club['midiclub_display'] = 1;
                $data_club['midiclub_type'] = array('IN','1,3');
                if (!empty($json_arr['city'])) {
                    $data_club['midiclub_city'] = $json_arr['city'];
                }
                if (!empty($json_arr['club_name'])) {
                    $data_club['midiclub_name'] = array('LIKE',"%{$json_arr['club_name']}%");
                }
                $midiclub_arr = M('midiclub')->field('midiclub_admin,midiclub_password,midiclub_token,midiclub_sig,midiclub_sigexpire',true)->alias('m')->join('midi_city as c on m.midiclub_city = c.city_id')->where($data_club)->select();
                $midiclubs = array();
                foreach ($midiclub_arr as $k => $v) {
                    $v['distance'] = getDistance($json_arr['my_lat'],$json_arr['my_lng'],$v['midiclub_lat'],$v['midiclub_lng']);
                    array_push($midiclubs, $v);
                }
                foreach ($midiclubs as $k => $v) {
                    $distance[$k] = $v['distance'];
                }
                array_multisort($distance,SORT_ASC,$midiclubs);
                $result = page_array($p,$pnum,$midiclubs);
                $this->backToClient(1,'获取迷笛club列表成功！',$result);
                break;
            default:
                $this->backToClient(2,'必要参数传入错误');
                break;
        }

    }

    /**
     * 曲谱教程列表
     * @author xuan
     * @param type          类型 1曲谱 2教程
     */
    public function goodsList(){
        $json_arr = $this->Security();
        $data['goods_category'] = $json_arr['type'];
        $data['goods_display'] = 1;
        if ($data['goods_category'] == 1 || $data['goods_category'] == 2) {
            $lowest = M('goods')->alias('g')->field('g.goods_price,c.goodscategory_content')->where($data)->join('midi_goodscategory as c on g.goods_category = c.goodscategory_id')->order('g.goods_price asc')->find();
            $result['lowest'] = $lowest['goods_price'];
            $highest = M('goods')->alias('g')->field('g.goods_price,c.goodscategory_content')->where($data)->join('midi_goodscategory as c on g.goods_category = c.goodscategory_id')->order('g.goods_price desc')->find();
            $result['highest'] = $highest['goods_price'];
            //商品类型详情
            $result['details'] = $highest['goodscategory_content'];
            $this->backToClient(1,'获取曲谱列表成功！',$result);
        }else{
            $this->backToClient(101,'类型参数错误');
        }

    }

    /**
     * 获取商品详情
     * @author xuan
     * @param type          类型 1曲谱 2教程
     * @param major_id      专业id 1电吉他 2爵士鼓 3电贝司
     * @param level         等级
     */
    public function goodsDetails(){
        $json_arr = $this->Security();
        // $json_arr['type'] = 1;
        // $json_arr['major_id'] = 1;
        // $json_arr['level'] = 1;
        if (empty($json_arr['type']) || empty($json_arr['major_id']) || empty($json_arr['level'])) {
            $this->backToClient(101,'参数不全');
        }
        $data['goods_category'] = $json_arr['type'];
        $data['goods_major_id'] = $json_arr['major_id'];
        $data['goods_level'] = $json_arr['level'];
        $data['goods_display'] = 1;
        $freight_arr = M('freight')->find();
        if ($goods = M('goods')->where($data)->find()) {
        	$goods['freight'] = $freight_arr['freight_price'];
            $this->backToClient(1,'获取商品详情成功',$goods);
        }else{
            $this->backToClient(1,'没有该商品');
        }
    }

    /**
     * 备考指南
     * @author xuan
     * @param type          类型 1电吉他 2爵士鼓 3电贝司（必填）
     * @param level         等级 1-9（必填）
     */
    public function examGuide(){
        $json_arr = $this->Security();
        // $json_arr['type'] = 1;
        // $json_arr['level'] = 1;
        if (empty($json_arr['type']) || empty($json_arr['level'])) {
            $this->backToClient(2,'参数不全');
        }
        //文章
        $data_article['article_type'] = $json_arr['type'];
        $data_article['article_level'] = $json_arr['level'];
        $article = M('Article')->where($data_article)->find();
        //相关视频
        $data_video['video_major_id'] = $json_arr['type'];
        $data_video['video_level'] = $json_arr['level'];
        $data_video['video_display'] = 1;
        $video = M('video')->where($data_video)->limit(2)->select();
        //相关曲谱教程
        $data_goods['goods_major_id'] = $json_arr['type'];
        $data_goods['goods_level'] = $json_arr['level'];
        $data_goods['goods_display'] = 1;
        $goods = M('goods')->where($data_goods)->find();
        //商品运费
        $freight = M('freight')->find();
        $goods['freight'] = $freight['freight_price'];
        //相关音频
        $data_audio['audio_major_id'] = $json_arr['type'];
        $data_audio['audio_level'] = $json_arr['level'];
        $data_audio['audio_display'] = 1;
        $audio = M('audio')->where($data_audio)->limit(2)->select();
        //整合返回
        $result = array();
        $result['article'] = $article;
        $result['video'] = $video;
        $result['goods'] = $goods;
        $result['audio'] = $audio;
        $this->backToClient(1,'获取备考指南信息成功',$result);
    }

    /**
     * 关于迷笛
     * @author xuan
     */
    public function aboutMIDI(){
        $json_arr = $this->Security();
        $data['article_type'] = 5;
        $article = M('Article')->field('article_id,article_title,article_url,article_pic')->where($data)->select();
        foreach ($article as $k => $v) {
            $article[$k]['article_url'] = 'http://47.93.115.108/index.php/App/User/article_details/id/'.$v['article_id'];
        }
        $this->backToClient(1,'获取关于迷笛列表成功',$article);
    }

    /**
     * 音频详情
     * @author xuan
     * @param audio_id         音频id（必填）
     * @param major_id         类型 1电吉他 2爵士鼓 3电贝司（必填）
     * @param level            等级 1-9（必填）
     */
    public function audioDetails(){
        $json_arr = $this->Security();
        // $json_arr['audio_id'] = 1;
        // $json_arr['major_id'] = 1;
        // $json_arr['level'] = 1;
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        //相关视频
        $data_video['video_major_id'] = $json_arr['major_id'];
        $data_video['video_level'] = $json_arr['level'];
        $data_video['video_display'] = 1;
        $video = M('video')->where($data_video)->order('rand()')->limit(2)->select();
        //相关曲谱教程
        $data_goods['goods_major_id'] = $json_arr['major_id'];
        $data_goods['goods_level'] = $json_arr['level'];
        $data_goods['goods_display'] = 1;
        $goods = M('goods')->where($data_goods)->find();
        //商品运费
        $freight = M('freight')->find();
        $goods['freight'] = $freight['freight_price'];
        //音频评论
        $data_comment['comment_object'] = 2;
        $data_comment['comment_object_id'] = $json_arr['audio_id'];
        $comment = M('comment')->alias('c')->join('left join midi_user as u on c.comment_user_id = u.user_id')->field('c.*,u.user_nickname,u.user_avatar')->where($data_comment)->page($p,$pnum)->order('comment_id desc')->select();
        //整合返回
        $result = array();
        $result['video'] = $video;
        $result['goods'] = $goods;
        $result['comment'] = $comment;
        $this->backToClient(1,'获取音频详情成功',$result);
    }

    /**
     * 视频详情
     * @author xuan
     * @param video_id         视频id（必填）
     * @param major_id         类型 1电吉他 2爵士鼓 3电贝司（必填）
     * @param level            等级 1-9（必填）
     */
    public function videoDetails(){
        $json_arr = $this->Security();
        // $json_arr['video_id'] = 1;
        // $json_arr['major_id'] = 1;
        // $json_arr['level'] = 1;
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        //相关视频
        $data_video['video_major_id'] = $json_arr['major_id'];
        $data_video['video_level'] = $json_arr['level'];
        $data_video['video_id'] = array('NEQ',$json_arr['video_id']);
        $data_video['video_display'] = 1;
        $video = M('video')->where($data_video)->limit(2)->select();
        //相关曲谱教程
        $data_goods['goods_major_id'] = $json_arr['major_id'];
        $data_goods['goods_level'] = $json_arr['level'];
        $data_goods['goods_display'] = 1;
        $goods = M('goods')->where($data_goods)->find();
        //商品运费
        $freight = M('freight')->find();
        $goods['freight'] = $freight['freight_price'];
        //相关音频
        $data_audio['audio_major_id'] = $json_arr['major_id'];
        $data_audio['audio_level'] = $json_arr['level'];
        $data_audio['audio_display'] = 1;
        $audio = M('audio')->where($data_audio)->limit(2)->select();
        //整合返回
        $result = array();
        $result['video'] = $video;
        $result['goods'] = $goods;
        $result['audio'] = $audio;
        $this->backToClient(1,'获取视频详情成功',$result);
    }

    /**
     * 有考试的考点列表(线下考试)
     * @author xuan
     * @param city_id            城市id（选填）
     * @param club_name          考点名称（选填）
     */
    public function offlineRoomList(){
        $json_arr = $this->Security();
        //4个小时
        $now = date('Y-m-d',time()+4*60*60);
        $data['midiclub_display'] = 1;
        if (!empty($json_arr['city_id'])) {
            $data['midiclub_city'] = $json_arr['city_id'];
        }
        if (!empty($json_arr['club_name'])) {
            $data['midiclub_name'] = array('LIKE',"%{$json_arr['club_name']}%");
        }
        $offline = M('examoffline')->alias('e')->join('left join midi_midiclub as m on e.examoffline_roomid = m.midiclub_id')->field('e.examoffline_roomid,m.midiclub_name,m.midiclub_address')->where($data)->where("e.examoffline_ymd > '".$now."'")->group('e.examoffline_roomid')->select();
        $this->backToClient(1,'获取有考试的考点列表成功',$offline);
    }

    /**
     * 有考试的考点时间表(线下考试)
     * @author xuan
     * @param room_id          考点id（必填）
     */
    public function offlineExamTime(){
        $json_arr = $this->Security();
        // $json_arr['room_id'] = 1;
        if (empty($json_arr['room_id'])) {
            $this->backToClient(2,'参数不全');
        }
        //4个小时
        $now = date('Y-m-d H:i:s',(time()+4*60*60));
        $data['examoffline_roomid'] = $json_arr['room_id'];
        $exam_arr = M('examoffline')->field('examoffline_id,examoffline_ymd,(examoffline_max_guitar - examoffline_already_guitar) as guitar_allow_count,(examoffline_max_drum - examoffline_already_drum) as drum_allow_count,(examoffline_max_bass - examoffline_already_bass) as bass_allow_count')->where($data)->where("examoffline_ymd > '".$now."'")->order('examoffline_ymd desc')->select();
        $this->backToClient(1,'获取线下考试考点时间表成功',$exam_arr);
    }

    /**
     * 考试时间段（线上考试）
     * @author xuan
     * @param exam_ymd            考试时间年月日（必填）
     * @param exam_major_id       专业id 1电吉他 2爵士鼓 3电贝司（必填）
     */
    public function onlineExamTime(){
        $json_arr = $this->Security();
        // $json_arr['exam_ymd'] = '2016-09-21';
        // $json_arr['exam_major_id'] = 1;
        if (empty($json_arr['exam_ymd']) || empty($json_arr['exam_major_id'])) {
            $this->backToClient(2,'报名信息不全！');
        }
        if ($json_arr['exam_major_id'] == 1) {
            $data['user_examiner_guitar'] = 1;
        }elseif ($json_arr['exam_major_id'] == 2) {
            $data['user_examiner_drum'] = 1;
        }elseif ($json_arr['exam_major_id'] == 3) {
            $data['user_examiner_bass'] = 1;
        }else{
            $this->backToClient(3,'专业id错误！');
        }
        //用户存在
        $data['user_display'] = 1;
        //考官身份
        $data['user_role'] = array('IN','3,4');
        //获取所有考官id
        $user_ids = M('user')->where($data)->getField('user_id',true);
        $examiner_ids = implode(',', $user_ids);
        $condition['examoptions_user_id'] = array('IN',$examiner_ids);
        $condition['examoptions_ymd'] = $json_arr['exam_ymd'];
        //获取所有那一天有考试设置的考官
        $examiner_arr = M('examoptions')->where($condition)->select();
        //遍历时间段
        $examtime = M('examtime')->select();
        foreach ($examtime as $key=>$value) {
            $id_arr = array();
            foreach ($examiner_arr as $k => $v) {
                if (inString($value['examtime_id'],$v['examoptions_time']) && !inString($value['examtime_id'],$v['examoptions_ordertime']) && (date('Y-m-d H:i',time()+30*60) < $condition['examoptions_ymd'].' '.$value['examtime_hi'])) {
                    $id_arr[] = $v['examoptions_user_id'];
                }
            }
            if (empty($id_arr)) {   //无考官
                $examtime[$key]['examiner_count'] = 0;
            }else{
                $examtime[$key]['examiner_count'] = count($id_arr);
                $index = array_rand($id_arr);
                $examtime[$key]['examiner_id'] = $id_arr[$index];
            }
        }
        $this->backToClient(1,'获取线上考试时间段成功！',$examtime);
    }

    /**
     * 获取考试报名费
     * @author xuan
     * @param major_id          专业id 1电吉他 2爵士鼓 3电贝司 4乐理考试
     * @param level             等级1-9
     * @param log               是否有考试记录 1否 2是（必填）
     */
    public function examFee(){
        $json_arr = $this->Security();
        // $json_arr['major_id'] = 2;
        // $json_arr['level'] = 4;
        // $json_arr['log'] = 1;
        if (empty($json_arr['major_id']) || empty($json_arr['level']) || empty($json_arr['log'])) {
            $this->backToClient(2,'参数不全');
        }
        $data['major_id'] = $json_arr['major_id'];
        $major = M('major')->where($data)->find();
        if ($json_arr['level'] == 1 || $json_arr['log'] == 2) {
            $key = 'major_cost'.$json_arr['level'];
            $fee = $major[$key];
        }else{
            $key1 = 'major_cost'.$json_arr['level'];
            $key2 = 'major_cost'.($json_arr['level']-1);
            $fee = $major[$key1]+$major[$key2];
        }

        $this->backToClient(1,'获取考试报名费成功！',$fee);
    }

    /**
     * 获取考试记录
     * @author xuan
     * @param id                用户midiID
     */
    public function examLog(){
        $json_arr = $this->Security();
        // $json_arr['id'] = 9595;
        if (empty($json_arr['id'])) {
            $this->backToClient(2,'参数不全');
        }
        $where['user_id'] = $json_arr['id'];
        $user = M('user')->where($where)->find();
        if (empty($user)) {
            $this->backToClient(3,'用户不存在');
        }
        $result = array();
        $data['exam_user_id'] = $json_arr['id'];
        $data['exam_status'] = 3;
        $data['exam_paystatus'] = 2;
        $data['exam_major_id'] = 1;
        //电吉他
        $exam_arr = M('exam')->where($data)->select();
        if (empty($exam_arr)) {
            $result['guitar'] = array('log'=>1,'level'=>$user['user_level_guitar']);
        }else{
            $result['guitar'] = array('log'=>2,'level'=>$user['user_level_guitar']);
        }
        //爵士鼓
        $data['exam_major_id'] = 2;
        $exam_arr = M('exam')->where($data)->select();
        if (empty($exam_arr)) {
            $result['drum'] = array('log'=>1,'level'=>$user['user_level_drum']);
        }else{
            $result['drum'] = array('log'=>2,'level'=>$user['user_level_drum']);
        }
        //电贝司
        $data['exam_major_id'] = 3;
        $exam_arr = M('exam')->where($data)->select();
        if (empty($exam_arr)) {
            $result['bass'] = array('log'=>1,'level'=>$user['user_level_bass']);
        }else{
            $result['bass'] = array('log'=>2,'level'=>$user['user_level_bass']);
        }
        $this->backToClient(1,'获取考试记录成功',$result);
    }

    /**
     * 报名
     * @author xuan
     * @param exam_user_id        考生id（必填）
     * @param exam_examiner_id    考官id（线上考试必填）
     * @param exam_major_id       专业id 1电吉他 2爵士鼓 3电贝司（必填）
     * @param exam_level          专业等级1-9（必填）
     * @param exam_ymd            考试时间年月日,格式'Y-m-d'（必填）
     * @param exam_time           考试时间段（线上必填）
     * @param exam_midiclub_id    考场id（线上考试请传-1）（必填）
     * @param exam_cost           报名费用（必填）
     * @param exam_certaddress    证书邮寄地址（必填）
     * @param pay_type            支付方式 1微信 2支付宝（必填）
     */
    public function applyExam(){
        $json_arr = $this->Security();
        // $json_arr['exam_user_id'] = 5;
        // $json_arr['exam_examiner_id'] = 6;       //（线上考试参数）
        // $json_arr['exam_major_id'] = 1;
        // $json_arr['exam_level'] = 8;
        // $json_arr['exam_ymd'] = '2016-09-21';    //（线上考试参数）
        // $json_arr['exam_time'] = 6;              //（线上考试参数）
        // $json_arr['exam_midiclub_id'] = -1;
        // $json_arr['exam_certaddress'] = '北京市海淀区上地南路';
        // $json_arr['exam_cost'] = 0.01;
        if (in_array($json_arr['exam_user_id'], array('10387','10388','10389','10390','10391'))) {
            $json_arr['exam_cost'] = 0.01;
        }
        //个人认证状态
        $user_auth = M('user')->where('user_id = '.$json_arr['exam_user_id'])->getField('user_auth');
        if ($user_auth == 1) {
            $this->backToClient(2,'个人认证信息未提交！');
        }elseif ($user_auth == 2) {
            $this->backToClient(3,'个人认证信息正在审核中。。。');
        }elseif ($user_auth == 4) {
            $this->backToClient(4,'个人认证信息审核未通过，请检查后重新提交');
        }
        //线上考试，必须传入日期和考官id，线下考试不需要传
        if (empty($json_arr['exam_midiclub_id'])) {
            $this->backToClient(5,'考试类型参数错误');
        }elseif ($json_arr['exam_midiclub_id'] == -1) {     //线上考试
            if (empty($json_arr['exam_examiner_id'])) {
                $this->backToClient(6,'还未选择考官');
            }elseif (empty($json_arr['exam_time'])) {
                $this->backToClient(10,'还未选择时间段');
            }
        }
        if (empty($json_arr['exam_major_id'])) {
            $this->backToClient(7,'还未选择专业');
        }elseif (empty($json_arr['exam_level'])) {
            $this->backToClient(8,'还未选择等级');
        }elseif (empty($json_arr['exam_ymd'])) {
            $this->backToClient(9,'还未选择日期');
        }
        //查看该考生是否已经报名过了(已缴费)？
        $check['exam_user_id'] = $json_arr['exam_user_id'];
        $check['exam_ymd'] = $json_arr['exam_ymd'];
        $check['exam_paystatus'] = 2;	//已缴费
        $check['exam_status'] = 1;		//报名成功
        if (!empty($json_arr['exam_time'])) {
            $check['exam_time'] = $json_arr['exam_time'];
        }
        if (M('exam')->where($check)->find()) {
            $this->backToClient(15,'您之前已经报过名了');
        }
        //报名时间
        $json_arr['exam_applytime'] = time();
        //报名订单号
        $json_arr['exam_num'] = 'KS'.createOrdernum();
        //如果是线上考试，再次检验该时间段，考官是否空闲
        $options = array();
        $examoffline_arr = array();
        if ($json_arr['exam_midiclub_id'] == -1) {
            if ($json_arr['exam_level'] > 4) {  //线上考试最高等级是4级
                $this->backToClient(16,'线上考试最高等级是4级');
            }
            $options_data['examoptions_user_id'] = $json_arr['exam_examiner_id'];
            $options_data['examoptions_ymd'] = $json_arr['exam_ymd'];
            $options = M('examoptions')->where($options_data)->find();
            if (empty($options)) {
                $this->backToClient(12,'考试不存在');
            }
            if (!inString($json_arr['exam_time'],$options['examoptions_time']) || inString($json_arr['exam_time'],$options['examoptions_ordertime'])) {
                $this->backToClient(11,'该考官已有预约，请重新报名！');
            }
            //考官收益
            $examiner = M('user')->field('user_income_proportion')->where('user_id = '.$json_arr['exam_examiner_id'])->find();
            $json_arr['exam_income'] = $examiner['user_income_proportion'] * $json_arr['exam_cost'];
        }else{      //如果是线下，查看是否超过考场设置最大人数
            $offline_data['examoffline_roomid'] = $json_arr['exam_midiclub_id'];
            $offline_data['examoffline_ymd'] = $json_arr['exam_ymd'];
            //最大人数
            $examoffline_arr = M('examoffline')->where($offline_data)->find();
            if (empty($examoffline_arr)) {
                $this->backToClient(12,'考试不存在');
            }
            $max_count = 0;
            if ($json_arr['exam_major_id'] == 1) {
                $max_count = $examoffline_arr['examoffline_max_guitar'];
            }elseif ($json_arr['exam_major_id'] == 2) {
                $max_count = $examoffline_arr['examoffline_max_drum'];
            }elseif ($json_arr['exam_major_id'] == 3) {
                $max_count = $examoffline_arr['examoffline_max_bass'];
            }
            //当前报名成功的人数
            $exam_data['exam_midiclub_id'] = $json_arr['exam_midiclub_id'];
            $exam_data['exam_ymd'] = $json_arr['exam_ymd'];
            $exam_data['exam_major_id'] = $json_arr['exam_major_id'];
            $exam_data['exam_status'] = 1;
            $apply_count = M('exam')->where($exam_data)->count();
            if ($apply_count >= $max_count) {
                $this->backToClient(13,'该专业考试已达到最大人数！');
            }
        }
        //添加信息到exam表中
        if($data['exam_id'] = M('exam')->add($json_arr)){
            //报名成功，考官的这个时间段暂时被占用（缴费成功，则不需要修改，若缴费失败，则再把时间改回）
            if (!empty($options)) { //线上考试
            	if (empty($options['examoptions_ordertime'])) {
            		$options['examoptions_ordertime'] = $json_arr['exam_time'];
            	}else{
            		$ordertime = explode(',', $options['examoptions_ordertime']);
	                array_push($ordertime, $json_arr['exam_time']);
	                $options['examoptions_ordertime'] = implode(',', $ordertime);
            	}
	            M('examoptions')->save($options);

            }
            //根据客户端所需要的参数，返回数据（暂时全部返回）
            $exam_arr = M('exam')->where($data)->find();
            //报名成功，线下考试，考场人数+1
            if ($examoffline_arr) {
                if ($json_arr['exam_major_id'] == 1) {
                    $examoffline_arr['examoffline_already_guitar'] += 1;
                }elseif ($json_arr['exam_major_id'] == 2) {
                    $examoffline_arr['examoffline_already_drum'] += 1;
                }elseif ($json_arr['exam_major_id'] == 3) {
                    $examoffline_arr['examoffline_already_bass'] += 1;
                }
                M('examoffline')->save($examoffline_arr);
            }
            if ($json_arr['pay_type'] == 1) {
                Vendor('Wxpay.Weixinpay');
                $exam_config['body'] = '迷笛考级报名';
                $exam_config['out_trade_no'] = $exam_arr['exam_num'];
                $exam_config['total_fee'] = $exam_arr['exam_cost'] * 100;
                $weixin_config = C(WEIXINPAY_CONFIG);
                $exam_config['notify_url'] = $weixin_config['exam_notify'];
                $wxpay = new \Weixinpay();
                $result = $wxpay->unifiedOrder($exam_config);
                if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
                    $arr['appid'] = $result['appid'];
                    $arr['noncestr'] = $result['nonce_str'];
                    $arr['package'] = $result['package'];
                    $arr['partnerid'] = $result['mch_id'];
                    $arr['prepayid'] = $result['prepay_id'];
                    $arr['timestamp'] = $result['timestamp'];
                    $arr['sign'] = $wxpay->MakeSign($arr);
                    $arr['exam_num'] = $exam_arr['exam_num'];
                    $arr['exam_cost'] = $exam_arr['exam_cost'];
                    $this->backToClient(1,'考试报名成功',$arr);
                }else{
                    $this->backToClient(4,'支付订单失败');
                }
            }elseif ($json_arr['pay_type'] == 2) {
                Vendor('Alipay.Alipay');
                $alipay = new \Alipay();
                $ali_arr['out_trade_no'] = $exam_arr['exam_num'];
                $ali_arr['subject'] = '迷笛考级报名费';
                $ali_arr['body'] = '迷笛考级报名费';
                $ali_arr['total_fee'] = $exam_arr['exam_cost'];
                $ali_config = C(ALIPAY_CONFIG);
                $ali_arr['notify_url'] = $ali_config['exam_notify'];
                $ali_result = $alipay->unifiedOrder($ali_arr);
                $this->backToClient(1,'考试报名成功',$ali_result);
            }else{
                $this->backToClient(15,'未选择支付方式');
            }
        }else{
            $this->backToClient(14,'报名失败！');
        }
    }

    /**
     * 已支付订单(分页)
     * @author xuan
     * @param user_id           用户id
     */
    public function paidOrder(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 1;
        if (empty($json_arr['user_id'])) {
            $this->backToClient(2,'参数不全');
        }
        $data['order_user_id'] = $json_arr['user_id'];
        $data['order_paystatus'] = array('IN','2,3');
        $data['order_display'] = 1;
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        $orders = M('order')->where($data)->order('order_id desc')->page($p,$pnum)->select();
        if (!empty($orders)) {
            foreach ($orders as $k => $v) {
                //收货地址
                $address_id = $v['order_address'];
                $address_arr = M('address')->where('address_id = '.$address_id)->find();
                $orders[$k]['addressdetails'] = $address_arr;
                //订单商品详情(1:4,2:2,3:1)
                $order_details = $v['order_details'];
                $a = explode(',', $order_details);
                $goods_c = 0;
                foreach ($a as $kk => $vv) {
                    $goods = explode(':', $vv);
                    $goodsid = $goods[0];
                    $goodscount = $goods[1];
                    $goods_c += $goodscount;
                    $goods_arr = array();
                    $goods_arr = M('goods')->where('goods_id = '.$goodsid)->find();
                    $goods_arr['goods_count'] = $goodscount;
                    $orders[$k]['goodsdetails'][$kk] = $goods_arr;
                }
                $orders[$k]['goods_total_count'] = $goods_c;
            }
        }else{
            $orders = array();
        }
        $this->backToClient(1,'获取已支付订单成功',$orders);
    }

    /**
     * 删除订单
     * @author xuan
     * @param user_id           用户id
     * @param order_id          订单id
     */
    public function delOrder(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 1;
        // $json_arr['order_id'] = 1;
        if (empty($json_arr['user_id']) || empty($json_arr['order_id'])) {
            $this->backToClient(2,'参数不全');
        }
        $data['order_id'] = $json_arr['order_id'];
        $data['order_user_id'] = $json_arr['user_id'];
        $data['order_display'] = 0;
        if (M('order')->save($data)) {
            $this->backToClient(1,'删除订单成功');
        }else{
            $this->backToClient(3,'删除订单失败');
        }
    }

    /**
     * 创建订单
     * @author xuan
     * @param user_id           买家id(必传)
     * @param details           订单详情（商品id:数量,商品id:数量）(必传)
     * @param totalprice        订单总价(必传)
     * @param address           收货地址id(必传)
     * @param express_price     运费价格(必传)
     * @param pay_type          支付方式1微信 2支付宝(必传)
     */
    public function createOrder(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 1;
        // $json_arr['details'] = '2:4';
        // $json_arr['totalprice'] = 0.01;
        // $json_arr['address'] = 1;
        // $json_arr['pay_type'] = 2;
        if (empty($json_arr['user_id']) || empty($json_arr['details']) || empty($json_arr['totalprice']) || empty($json_arr['address']) || empty($json_arr['pay_type'])) {
            $this->backToClient(2,'参数不全');
        }
        $data['order_user_id'] = $json_arr['user_id'];
        $data['order_details'] = $json_arr['details'];
        $data['order_totalprice'] = $json_arr['totalprice'];
        $data['order_express_price'] = $json_arr['express_price'];
        $data['order_address'] = $json_arr['address'];
        $data['order_createtime'] = time();
        $data['order_num'] = createOrdernum();
        if ($orderid = M('order')->add($data)) {
            $order_arr = M('order')->where('order_id = '.$orderid)->find();
            //微信支付
            if ($json_arr['pay_type'] == 1) {
                Vendor('Wxpay.Weixinpay');
                $order_config['body'] = 'midi goods';
                $order_config['out_trade_no'] = $order_arr['order_num'];
                $order_config['total_fee'] = $order_arr['order_totalprice'] * 100;
                $weixin_config = C(WEIXINPAY_CONFIG);
                $order_config['notify_url'] = $weixin_config['goods_notify'];
                $wxpay = new \Weixinpay();
                $result = $wxpay->unifiedOrder($order_config);
                if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
                    $arr['appid'] = $result['appid'];
                    $arr['noncestr'] = $result['nonce_str'];
                    $arr['package'] = $result['package'];
                    $arr['partnerid'] = $result['mch_id'];
                    $arr['prepayid'] = $result['prepay_id'];
                    $arr['timestamp'] = $result['timestamp'];
                    $arr['sign'] = $wxpay->MakeSign($arr);
                    $arr['order_num'] = $order_arr['order_num'];
                    $arr['order_totalprice'] = $order_arr['order_totalprice'];
                    $this->backToClient(1,'创建订单成功',$arr);
                }else{
                    $this->backToClient(4,'支付订单失败');
                }
            }elseif ($json_arr['pay_type'] == 2) {  //支付宝支付
                Vendor('Alipay.Alipay');
                $alipay = new \Alipay();
                $ali_arr['out_trade_no'] = $order_arr['order_num'];
                $ali_arr['subject'] = '迷笛考级商品购买';
                $ali_arr['body'] = '迷笛考级商品购买';
                $ali_arr['total_fee'] = $order_arr['order_totalprice'];
                $ali_config = C(ALIPAY_CONFIG);
                $ali_arr['notify_url'] = $ali_config['goods_notify'];
                $ali_result = $alipay->unifiedOrder($ali_arr);
                $this->backToClient(1,'创建订单成功',$ali_result);
            }else{
                $this->backToClient(5,'支付方式错误');
            }

        }else{
            $this->backToClient(3,'创建订单失败');
        }
    }

    /**
     * 删除购物车某一项
     * @author xuan
     * @param user_id           买家id(必传)
     * @param goods_id          商品id(必传)
     */
    public function delOneGoods(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 2;
        // $json_arr['goods_id'] = 4;
        //例如 1:4,2:3,4:2
        if (empty($json_arr['user_id']) || empty($json_arr['goods_id'])) {
            $this->backToClient(2,'参数不全');
        }
        $data['shoppingcart_user_id'] = $json_arr['user_id'];
        $cart = M('shoppingcart')->where($data)->find();
        $details = $cart['shoppingcart_details'];
        $details_arr = explode(',', $details);
        foreach ($details_arr as $key => $value) {
            $one = explode(':', $value);
            if (inString($one[0],$json_arr['goods_id'])) {
                unset($details_arr[$key]);
            }
        }
        $cart['shoppingcart_details'] = implode(',', $details_arr);
        if (M('shoppingcart')->save($cart)) {
            $this->backToClient(1,'删除购物车某一项成功');
        }else{
            $this->backToClient(2,'删除购物车某一项失败');
        }
    }

    /**
     * 查询证书
     * @author xuan
     * @param type              类型 1两种证书查询 2迷笛先生资格认证证书（必填）
     * @param num               证书编号（1两种证书查询必填）
     * @param user_id           证书所有者（2专业等级证书必填）
     * @param major_id          专业id（2专业等级证书必填）
     * @param level             专业等级（2专业等级证书必填）
     */
    public function certificateSearch(){
        $json_arr = $this->Security();
        // $json_arr['type'] = 1;
        // $json_arr['num'] = 1;
        // $json_arr['user_id'] = 1;
        // $json_arr['major_id'] = 1;
        if ($json_arr['type'] == 1) {
            $data1['certificate_num'] = $json_arr['num'];
            $info = M('certificate')->alias('c')->field('user_avatar,user_name,user_sex,user_country,user_nation,user_birthday,certificate_num,certificate_time,certificate_major_id,certificate_level,certificate_type')->join('midi_user as u on c.certificate_user_id = u.user_id')->where($data1)->find();
            $this->backToClient(1,'获取证书信息成功',$info);
        }elseif ($json_arr['type'] == 2) {
            $data2['certificate_type'] = 2;
            $data2['certificate_user_id'] = $json_arr['user_id'];
            $data2['certificate_major_id'] = $json_arr['major_id'];
            // $data2['certificate_level'] = $json_arr['level'];
            $info = M('certificate')->alias('c')->field('user_avatar,user_name,user_sex,user_country,user_nation,user_birthday,certificate_id,certificate_num,certificate_time,certificate_major_id,certificate_level,certificate_type')->join('midi_user as u on c.certificate_user_id = u.user_id')->where($data2)->find();
            $this->backToClient(1,'获取证书信息成功',$info);
        }else{
            $this->backToClient(2,'类型参数错误');
        }
    }

    // 文章详情
    public function article_details(){
        $data['article_id'] = I('get.id');
        $article = M('article')->where($data)->find();
        $article['article_details'] = file_get_contents('.'.$article['article_url']);
        $this->assign('article',$article);
        $this->display();
    }

    /**
     * 获取练习考题
     * @author xuan
     */
    public function examPaper(){
        $json_arr = $this->Security();
        $url = U('App/User/createExampaper');
        $this->backToClient(1,'获取练习考题成功',$url);
    }

    /**
     * 52.获取消息详情
     * @author xuan
     * @param id 消息id
     */
    public function messageInfo(){
        $json_arr = $this->Security();
        // $json_arr['id'] = 6;
        if (empty($json_arr['id'])) {
            $this->backToClient(2,'参数不全');
        }
        $data['message_id'] = $json_arr['id'];
        $data['message_display'] = 1;
        $message = M('message')->where($data)->find();
        $this->backToClient(1,'获取消息详情成功',$message);
    }

    /**
     * 53.获取考试详情
     * @author xuan
     * @param id 考试id
     */
    public function examInfo(){
        $json_arr = $this->Security();
        // $json_arr['id'] = 48;
        if (empty($json_arr['id'])) {
            $this->backToClient(2,'参数不全');
        }
        $data['exam_id'] = $json_arr['id'];
        $exam_arr = M('exam')->alias('e')->field('exam_id,user_avatar,user_name,user_sex,exam_major_id,exam_level,exam_ymd,exam_comment,exam_result,user_idpic1,examtime_time')->join('left join midi_user as u on u.user_id = e.exam_user_id')->join('left join midi_examtime as t on e.exam_time = t.examtime_id')->where($data)->find();
        $this->backToClient(1,'获取考试详情成功！',$exam_arr);
    }

    /**
     * 54.获取工本费
     * @author xuan
     */
    public function bookFee(){
        $json_arr = $this->Security();
        $bookfee = M('bookfee')->find();
        $this->backToClient(1,'获取获取工本费成功！',$bookfee['bookfee_price']);
    }

    /**
     * 创建工本费订单
     * @author xuan
     * @param exam_id           考试id(必传)
     * @param pay_type          支付方式1微信 2支付宝(必传)
     */
    public function createBookOrder(){
        $json_arr = $this->Security();
        // $json_arr['exam_id'] = 1;
        // $json_arr['pay_type'] = 2;
        if (empty($json_arr['exam_id']) || empty($json_arr['pay_type'])) {
            $this->backToClient(2,'参数不全');
        }
        //工本费
        $bookfee_arr = M('bookfee')->find();
        $bookfee = $bookfee_arr['bookfee_price'];
        // $bookfee = 0.01;
        //获取考试信息
        $exam_arr = M('exam')->where('exam_id = '.$json_arr['exam_id'])->find();
        //创建一条订单
        $data['certorder_sn'] = 'c'.createOrdernum();
        $data['certorder_price'] = $bookfee;
        $data['certorder_examid'] = $json_arr['exam_id'];
        $data['certorder_createtime'] = time();
        if ($certorderid = M('certorder')->add($data)) {
            $certorder_arr = M('certorder')->where('certorder_id = '.$certorderid)->find();
            //微信支付
            if ($json_arr['pay_type'] == 1) {
                Vendor('Wxpay.Weixinpay');
                $order_config['body'] = '考级证书工本费';
                $order_config['out_trade_no'] = $certorder_arr['certorder_sn'];
                $order_config['total_fee'] = $certorder_arr['certorder_price'] * 100;
                $weixin_config = C(WEIXINPAY_CONFIG);
                $order_config['notify_url'] = $weixin_config['cert_notify'];
                $wxpay = new \Weixinpay();
                $result = $wxpay->unifiedOrder($order_config);
                if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
                    $arr['appid'] = $result['appid'];
                    $arr['noncestr'] = $result['nonce_str'];
                    $arr['package'] = $result['package'];
                    $arr['partnerid'] = $result['mch_id'];
                    $arr['prepayid'] = $result['prepay_id'];
                    $arr['timestamp'] = $result['timestamp'];
                    $arr['sign'] = $wxpay->MakeSign($arr);
                    $arr['certorder_sn'] = $certorder_arr['certorder_sn'];
                    $arr['certorder_price'] = $certorder_arr['certorder_price'];
                    $this->backToClient(1,'创建订单成功',$arr);
                }else{
                    $this->backToClient(4,'支付订单失败');
                }
            }elseif ($json_arr['pay_type'] == 2) {  //支付宝支付
                Vendor('Alipay.Alipay');
                $alipay = new \Alipay();
                $ali_arr['out_trade_no'] = $certorder_arr['certorder_sn'];
                $ali_arr['subject'] = '考级证书工本费';
                $ali_arr['body'] = '考级证书工本费';
                $ali_arr['total_fee'] = $certorder_arr['certorder_price'];
                $ali_config = C(ALIPAY_CONFIG);
                $ali_arr['notify_url'] = $ali_config['cert_notify'];
                $ali_result = $alipay->unifiedOrder($ali_arr);
                $this->backToClient(1,'创建订单成功',$ali_result);
            }else{
                $this->backToClient(5,'支付方式错误');
            }
        }else{
            $this->backToClient(3,'创建订单失败');
        }
    }







    /**
     * 上传文件接口
     * @author xuan
     */
    public function upload(){
        $json_arr = $this->Security();
        $finfo = upload($_FILES['file']);
        if ($finfo['status'] == 0) {
            $this->backToClient(4,$finfo['msg']);
        }else{
            $this->backToClient(1,'上传成功！',$finfo['filepath']);
        }
    }


    /**
     * 保存录像接口
     * @author xuan
     * @param exam_id           考试id(必传)
     * @param vid               录像vid(必传)
     */
    // public function saveRecord(){
    //     $json_arr = $this->Security();
    //     if (empty($json_arr['exam_id']) || empty($json_arr['vid'])) {
    //         $this->backToClient(2,'参数不全');
    //     }
    //     $data['record_examid'] = $json_arr['exam_id'];
    //     $data['record_vid'] = $json_arr['vid'];
    //     $data['record_createtime'] = time();
    //     if (M('record')->add($data)) {
    //         $this->backToClient(1,'保存录像成功！');
    //     }else{
    //         $this->backToClient(3,'保存录像失败！');
    //     }
    // }

    /**
     * 判断考试是否开始
     * @author xuan
     * @param exam_id           考试id(必传)
     */
    public function examStart(){
        $json_arr = $this->Security();
        if (empty($json_arr['exam_id'])) {
            $this->backToClient(2,'参数不全');
        }
        $data['exam_id'] = $json_arr['exam_id'];
        $exam_arr = M('exam')->alias('e')->where($data)->join('left join midi_examtime as t on e.exam_time = t.examtime_id')->find();
        if (empty($exam_arr)) {
            $this->backToClient(3,'考试不存在！');
        }
        //当前时间向前推1小时
        $now = date('Y-m-d H:i',time()+60*60);
        if ($now >= $exam_arr['exam_ymd'].' '.$exam_arr['examtime_hi']) {
            $condition['exam_id'] = $data['exam_id'];
            $condition['exam_start'] = 1;
            M('exam')->save($condition);
            $this->backToClient(1,'可以进去考试');
        }else{
            $this->backToClient(4,'考试尚未开始');
        }
    }

    /**
     * 创建房间
     * @author xuan
     * @param exam_id           考试id(必传)
     */
    // public function createRoom(){
    //     $json_arr = $this->Security();
    //     if (empty($json_arr['exam_id'])) {
    //         $this->backToClient(2,'参数不全');
    //     }
    //     $data['exam_id'] = $json_arr['exam_id'];
    //     $exam_arr = M('exam')->where($data)->find();
    //     if (empty($exam_arr)) {
    //         $this->backToClient(3,'考试不存在！');
    //     }
    //     $user_value = array('tag'=>array('examiner'.$exam_arr['exam_examiner_id']));
    //     push($user_value,'考生创建房间成功，请做好监考准备',C(JPUSH_EXAMINER),3,$data['exam_id']);
    //     //添加一条消息
    //     $message['message_user_id'] = $exam_arr['exam_examiner_id'];
    //     $message['message_client'] = 2;
    //     $message['message_type'] = 3;
    //     $message['message_title'] = '考生创建房间成功，请做好监考准备';
    //     $message['message_content'] = '考生创建房间成功，请做好监考准备';
    //     $message['message_extra'] = $json_arr['exam_id'];
    //     $message['message_time'] = time();
    //     M('message')->add($message);

    //     $this->backToClient(1,'考生创建房间成功！');
    // }


    /**
     * 获取有考试的机构列表（分页）
     * @author xuan
     * @param major_id           科目id 1电吉他 2爵士鼓 3电贝司(必传)
     * @param date               考试日期(必传)
     * @param city               城市id(必传)
     */
    public function getOrgExamList(){
        $json_arr = $this->Security();
        // $json_arr['major_id'] = 1;
        // $json_arr['date'] = '2017-12-07';
        // $json_arr['city'] = 1;
        if (empty($json_arr['major_id']) || empty($json_arr['date'])) {
            $this->backToClient(2,'参数不全');
        }
        if ($json_arr['major_id'] == 1) {
            $condition['examorg_guitar'] = 1;
        }elseif ($json_arr['major_id'] == 2) {
            $condition['examorg_drum'] = 1;
        }elseif ($json_arr['major_id'] == 3) {
            $condition['examorg_bass'] = 1;
        }else{
            $this->backToClient(3,'科目id错误');
        }
        $condition['examorg_date'] = $json_arr['date'];
        if (!empty($json_arr['city'])) {
            $condition['midiclub_city'] = $json_arr['city'];
        }
        $condition['examorg_status'] = 1;
        $condition['midiclub_display'] = 1;
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:10;
        $club_arr = M('examorg')->alias('e')->field('e.examorg_id,e.examorg_orgid,e.examorg_time,m.midiclub_name,m.midiclub_pic,m.midiclub_address')->join('left join midi_midiclub as m on e.examorg_orgid = m.midiclub_id')->page($p,$pnum)->where($condition)->select();
        $this->backToClient(1,'获取有考试的机构列表成功',$club_arr);
    }

    /**
     * 判断可否选择当前机构
     * @author xuan
     * @param user_id                   用户id(必传)
     * @param examorg_id                机构考试id(必传)
     */
    public function selectCurrentOrg(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 5836;
        // $json_arr['examorg_id'] = 23;
        if (empty($json_arr['user_id']) || empty($json_arr['examorg_id'])) {
            $this->backToClient(2,'参数不全');
        }
        //当前机构人数是否满员
        $examorg_arr = M('examorg')->where(['examorg_id'=>$json_arr['examorg_id']])->find();
        if ($examorg_arr['examorg_maxnum'] <= $examorg_arr['examorg_enrollnum']) {
            $this->backToClient(3,'该场考试报名已满');
        }elseif ($examorg_arr['examorg_status'] == 2) {
            $this->backToClient(4,'该场考试已经结束');
        }
        //是否已经报名过这次考试
        $enroll_arr = M('examorg_enroll')->where(['examorg_enroll_userid'=>$json_arr['user_id'],'examorg_enroll_examorgid'=>$json_arr['examorg_id'],'examorg_enroll_status'=>['IN','2,3']])->find();
        if (!empty($enroll_arr)) {
            $this->backToClient(5,'您之前已经报过名了');
        }
        $this->backToClient(1,'可以报名考试');
    }

    /**
     * 考试报名（机构端）
     * @author xuan
     * @param user_id           考生id（必填）
     * @param examorg_id        机构考试id（必填）
     * @param major_id          专业id 1电吉他 2爵士鼓 3电贝司（必填）
     * @param level             专业等级1-4（必填）
     * @param avatar            一寸照片（必填）
     * @param fee               报名费用（必填）
     * @param pay_type          支付方式 1微信 2支付宝（必填）
     */
    public function applyOrgExam(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 5836;
        // $json_arr['examorg_id'] = 24;
        // $json_arr['major_id'] = 1;
        // $json_arr['level'] = 4;
        // $json_arr['avatar'] = '/Upload/image/201712/18/5a37750b2d834.jpg';
        $json_arr['fee'] = 0.01;
        // $json_arr['pay_type'] = 2;
        //验证数据是否为空
        if (empty($json_arr['user_id']) || empty($json_arr['examorg_id']) || empty($json_arr['major_id']) || empty($json_arr['level']) || empty($json_arr['avatar']) || empty($json_arr['fee']) || empty($json_arr['pay_type'])) {
            $this->backToClient(2,'参数不全');
        }
        //个人认证状态
        $user_auth = M('user')->where(['user_id'=>$json_arr['user_id']])->getField('user_auth');
        if ($user_auth == 1) {
            $this->backToClient(2,'个人认证信息未提交！');
        }elseif ($user_auth == 2) {
            $this->backToClient(3,'个人认证信息正在审核中。。。');
        }elseif ($user_auth == 4) {
            $this->backToClient(4,'个人认证信息审核未通过，请检查后重新提交');
        }
        //当前机构人数是否满员
        $examorg_arr = M('examorg')->where(['examorg_id'=>$json_arr['examorg_id']])->find();
        if ($examorg_arr['examorg_maxnum'] <= $examorg_arr['examorg_enrollnum']) {
            $this->backToClient(5,'该场考试报名已满');
        }elseif ($examorg_arr['examorg_status'] == 2) {
            $this->backToClient(6,'该场考试已经结束');
        }
        //是否已经报名过这次考试
        $enroll_arr = M('examorg_enroll')->where(['examorg_enroll_userid'=>$json_arr['user_id'],'examorg_enroll_examorgid'=>$json_arr['examorg_id'],'examorg_enroll_status'=>['IN','2,3']])->find();
        if (!empty($enroll_arr)) {
            $this->backToClient(7,'您之前已经报过名了');
        }
        //报名考试不能超过4级
        if ($json_arr['level'] > 4) {
            $this->backToClient(8,'考试等级不能超过4级');
        }
        //考试报名编号
        $condition['examorg_enroll_sn'] = 'EORG'.createOrdernum();
        //考生id
        $condition['examorg_enroll_userid'] = $json_arr['user_id'];
        //机构考试id
        $condition['examorg_enroll_examorgid'] = $json_arr['examorg_id'];
        //机构id
        $condition['examorg_enroll_orgid'] = $examorg_arr['examorg_orgid'];
        //考官id
        $condition['examorg_enroll_examinerid'] = $examorg_arr['examorg_examinerid'];
        //报考科目 1电吉他 2爵士鼓 3电贝司
        $condition['examorg_enroll_major'] = $json_arr['major_id'];
        //科目等级1-4
        $condition['examorg_enroll_level'] = $json_arr['level'];
        //考试日期Y-m-d
        $condition['examorg_enroll_date'] = $examorg_arr['examorg_date'];
        //考试时间段 1上午 2下午 3全天
        $condition['examorg_enroll_time'] = $examorg_arr['examorg_time'];
        //考试曲目，随机6选2
        $exam_audio_arr = M('exam_audio')->where(['exam_audio_major'=>$json_arr['major_id'],'exam_audio_level'=>$json_arr['level']])->order('rand()')->limit(2)->select();
        $condition['examorg_enroll_audio1'] = $exam_audio_arr[0]['exam_audio_name'];
        $condition['examorg_enroll_audio2'] = $exam_audio_arr[1]['exam_audio_name'];
        //一寸照片地址
        $condition['examorg_enroll_avatar'] = $json_arr['avatar'];
        //报名费用
        $condition['examorg_enroll_fee'] = $json_arr['fee'];
        //支付方式 1微信 2支付宝
        $condition['examorg_enroll_pay_type'] = $json_arr['pay_type'];
        //开始报名时间
        $condition['examorg_enroll_create_time'] = time();
        //添加信息到examorg_enroll表中
        if($examorg_enroll_id = M('examorg_enroll')->add($condition)){
            $examorg_enroll_arr = M('examorg_enroll')->where(['examorg_enroll_id'=>$examorg_enroll_id])->find();
            if ($json_arr['pay_type'] == 1) {
                Vendor('Wxpay.Weixinpay');
                $examorg_config['body'] = '迷笛考级报名';
                $examorg_config['out_trade_no'] = $examorg_enroll_arr['examorg_enroll_sn'];
                $examorg_config['total_fee'] = $examorg_enroll_arr['examorg_enroll_fee'] * 100;
                $weixin_config = C(WEIXINPAY_CONFIG);
                $examorg_config['notify_url'] = $weixin_config['examorg_notify'];
                $wxpay = new \Weixinpay();
                $result = $wxpay->unifiedOrder($examorg_config);
                if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
                    $arr['appid'] = $result['appid'];
                    $arr['noncestr'] = $result['nonce_str'];
                    $arr['package'] = $result['package'];
                    $arr['partnerid'] = $result['mch_id'];
                    $arr['prepayid'] = $result['prepay_id'];
                    $arr['timestamp'] = $result['timestamp'];
                    $arr['sign'] = $wxpay->MakeSign($arr);
                    $arr['examorg_enroll_sn'] = $examorg_enroll_arr['examorg_enroll_sn'];
                    $arr['examorg_enroll_fee'] = $examorg_enroll_arr['examorg_enroll_fee'];
                    $this->backToClient(1,'考试报名成功',$arr);
                }else{
                    $this->backToClient(9,'支付订单失败');
                }
            }elseif ($json_arr['pay_type'] == 2) {
                Vendor('Alipay.Alipay');
                $alipay = new \Alipay();
                $ali_arr['out_trade_no'] = $examorg_enroll_arr['examorg_enroll_sn'];
                $ali_arr['subject'] = '迷笛考级报名费';
                $ali_arr['body'] = '迷笛考级报名费';
                $ali_arr['total_fee'] = $examorg_enroll_arr['examorg_enroll_fee'];
                $ali_config = C(ALIPAY_CONFIG);
                $ali_arr['notify_url'] = $ali_config['examorg_notify'];
                $ali_result = $alipay->unifiedOrder($ali_arr);
                $this->backToClient(1,'考试报名成功',$ali_result);
            }else{
                $this->backToClient(10,'未选择支付方式');
            }
        }else{
            $this->backToClient(11,'报名失败！');
        }
    }


    /**
     * 获取CLUB未考完的考试列表
     * @author xuan
     * @param org_id              机构id(必传)
     */
    public function getClubExamList(){
        $json_arr = $this->Security();
        // $json_arr['org_id'] = 1;
        if (empty($json_arr['org_id'])) {
            $this->backToClient(2,'参数不全');
        }
        $condition['examorg_orgid'] = $json_arr['org_id'];
        $condition['examorg_status'] = 1;
        $condition['midiclub_display'] = 1;
        $club_arr = M('examorg')->alias('e')->field('e.examorg_id,e.examorg_orgid,e.examorg_date,e.examorg_time,e.examorg_guitar,e.examorg_drum,e.examorg_bass,m.midiclub_name,m.midiclub_pic,m.midiclub_address')->join('left join midi_midiclub as m on e.examorg_orgid = m.midiclub_id')->order('examorg_date asc,examorg_time asc')->where($condition)->select();
        $this->backToClient(1,'获取CLUB未考完的考试列表成功',$club_arr);
    }


    /**
     * 获取证书查询url
     * @author xuan
     */
    public function getCertQueryURL(){
        $json_arr = $this->Security();
        $url = "http://www.kaojionline.com/yikao/index.shtml#";
        $this->backToClient(1,'获取证书查询url成功',$url);
    }

    /**
     * 我的考试（分页）
     * @author xuan
     * @param user_id        考生id（必填）
     * @param status         考试状态 2已报名 3已完成（必填）
     */
    public function myOrgExam(){
        $json_arr = $this->Security();
        // $json_arr['user_id'] = 10389;
        // $json_arr['status'] = 3;
        if (empty($json_arr['user_id']) || empty($json_arr['status'])) {
            $this->backToClient(2,'参数不全');
        }
        $condition['examorg_enroll_userid'] = $json_arr['user_id'];
        $condition['examorg_enroll_status'] = $json_arr['status'];
        $examorg_enroll_arr = M('examorg_enroll')->alias('e')->join('left join midi_midiclub as m on e.examorg_enroll_orgid = m.midiclub_id')->field('e.examorg_enroll_id,e.examorg_enroll_orgid,e.examorg_enroll_major,e.examorg_enroll_level,e.examorg_enroll_date,e.examorg_enroll_time,e.examorg_enroll_result,e.examorg_enroll_mark,e.examorg_enroll_comment,m.midiclub_name,m.midiclub_address,m.midiclub_pic')->where($condition)->order('examorg_enroll_status asc,examorg_enroll_date asc,examorg_enroll_time asc')->page($p,$pnum)->select();
        if (empty($examorg_enroll_arr)) {
            $examorg_enroll_arr = array();
        }
        $this->backToClient(1,'获取我的考试列表成功',$examorg_enroll_arr);
    }

    /**
     * 获取客服电话
     * @author xuan
     */
    public function getKefuTel(){
        $json_arr = $this->Security();
        $option_arr = M('option')->find();
        $this->backToClient(1,'获取客服电话成功',$option_arr['option_kefu_tel']);
    }





}